【发布时间】:2021-10-16 01:00:28
【问题描述】:
这里是 React 初学者,我正在使用 axios 从我的前端表单中发送正文。我在服务器端做了一个console.log,这就是我在request.body 中看到的。
req.body {
'{"body":"{\\"firstName\\":\\"daf\\",\\"lastName\\":\\"afa\\",\\"address\\":\\"af\\",\\"phoneNumber\\":\\"123-933-6177\\",\\"email\\":\\"asfa\\",\\"facilityName\\":\\"afs\\",\\"isSeller\\":false}"}': ''
}
我在上面打印错误字符串的类
checkIfDuplicateEmailAndFacilityNameOnSignUp = (req, res, next) => {
// get the customer name
console.log("request", req.body.firstName);
const updatedBody = JSON.parse(req.body);
console.log(updatedBody);
Customer.findOne({
where: {
email: req.body.email
}
}).then(customerEmail => {
if (customerEmail) {
res.status(400).send({
message: "This email is already in use"
});
return;
}
Customer.findOne({
where: {
facilityName: req.body.facilityName
}
}).then(facilityname => {
if (facilityname) {
res.status(400).send({
message: "Facility exists already exists"
});
return;
}
next();
});
});
};
这是我从前端发帖的功能
const onFormSubmit = (event) => {
event.preventDefault();
const formBody = {
...this.state,
};
axios({
method: "POST",
url: "http://localhost:3000/api/auth/signup",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: {
body: formBody,
},
}).then((response) => {
console.log("response", response);
console.log("response data", response.data);
});
console.log("form submission done");
};
状态对象
state = {
firstName: "",
lastName: "",
address: "",
phoneNumber: "",
email: "",
facilityName: "",
isSeller: false,
};
这是我的节点 server.js 文件
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(
cors({
origin: "*",
})
);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
require('./app/routes/authRoutes')(app);
require('./app/routes/customerRoutes')(app);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Now listening on port ${PORT}`);
});
db.sequelize.sync({
force: true
})
.then(() => {
console.log("Dropping and Resync DB");
initial();
});
// creates roles in database for us
function initial() {
Role.create({
id: 1,
roleType: "buyer"
});
Role.create({
id: 2,
roleType: "seller"
});
};
我尝试使用 JSON.parse(),但收到消息 Unexpected token o in JSON at position 1 的异常。关于如何解析这个有什么想法吗?
更新 1:
根据@Bravo 回答更改后,身体现在看起来像这样
body: {
firstName: 'safds',
lastName: 'asf',
address: 'adfs',
phoneNumber: '404-932-6177',
email: 'asdf',
facilityName: 'afs',
isSeller: false
}
可能是一个愚蠢的问题,但我如何访问这些字段。我尝试做 body.firstName 或 body[0] 但我得到未定义的返回?
【问题讨论】:
-
Unexpected token o in JSON at position 1... 试图传递 string[object Object]的经典案例 .. 某处的某些东西正在强制一个对象变成一个字符串 - 你不这样做太糟糕了'不显示“我尝试使用 JSON.parse”的位置 -
现在更新@Bravo
-
您需要发送数据:作为
"Content-Type": "application/x-www-form-urlencoded"的“查询字符串”
标签: javascript node.js json axios