我有一个正在尝试完成的应用程序,它有一个表单,其中包含应发送到后端的数据,以便可以将其保存到 mongo db。我目前正在尝试将其显示到后端控制台以验证它是否已正确发送,到目前为止,当我在生产服务器上运行时我能够看到有效负载,但我无法获取任何信息来存储到我的数据库。我的 mongo db 正在尝试访问数据,但它所做的只是为用户文件创建一个文件夹,其中应该存储信息,但文件夹本身是空的。
我做错了什么?
这是我尝试连接的服务器
app.set('port', 8080);
// app.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(cors());
require('./config/mongo');
app.post("/backend/endpoint/v6", v6, (req, res) => {
let firstName = req.body.firstName;
console.log(firstName);
res.send(`
Your firstName is: ${firstName}
`);
});
这是前端
const onFinish = async values => {
values.phoneNumber = values.prefix + values.phoneNumber.match(/[0-9]+/g).join('');
setLoading(true)
values.birthDate = values.birthDate.format('MM/DD/YYYY')
const {firstName = values;
const data = new FormData();
data.append("firstName", firstName);
let response = await api.registerUser(data);
if (response.status === 200) {
const {data, token} = await response.json();
let obj = {};
obj.token = token;
obj.firstName = data.firstName;
dispatch(login(obj))
setSaved(true)
props.next()
} else
if (form) {
form.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(form);
axios
.post("backend/endpoint/v6", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
});
}
{
let data = await response.json()
message.error({
content: (<AlertMessage title="Error" content={data.message} status="error"/>),
className: 'custom-class custom_message_container',
icon: (<></>),
duration: 2
});
}
setLoading(false)
};
const onFinishFailed = errorInfo => {
console.log('Failed:', errorInfo);
};
return (
<>
<div className="steps_component">
<div className="steps_content_heading ">
<div className="steps_content_heading1">
Personal Info
</div>
<div className="steps_content_heading2">
Please enter your information and register.
</div>
</div>
<div>
<Form action="backend/endpoint/v6" method="POST" encType="multipart/form-date"
form={form}
name="basic"
initialValues={{remember: true, prefix: '+1'}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Row gutter={[16, 16]} style={{marginBottom: 0}}>
<Col span={12} style={{margin: 0}}>
<div className="form_label">First Name</div>
<Form.Item
style={{marginBottom: 0}}
name="firstName"
rules={[
{pattern: new RegExp(/^[a-zA-Z+']+$/),message: "Only Letters may be entered into the first name field"},
{required: true, message: 'Please enter first name'}]}
>
<Input placeholder="First Name"/>
</Form.Item>
当我尝试注册用户时,当前遇到此错误“无法在“响应”上执行“json”:正文流已读取” 类型错误:无法在“响应”上执行“json”:主体流已读取 在 onFinish (http://localhost:3000/static/js/bundle.js:5392:33) 处,它来自这一行“ let data = wait response.json() “所以我认为这意味着信息被多次发送到后端控制台但无法读取?我在这里做错了什么,我该如何修复它?欢迎任何帮助。
仅根据错误,我认为您(在前端)调用了
response.json()
两次,这是不允许的。使用变量来存储结果以便多次使用