JSON 中的意外令牌 o 在位置 1 获取请求
Unexpected token o in JSON at position 1 fetch request
我正在尝试向我的 api 服务器发出 POST 获取请求以做出反应,无论我如何发送数据,我都会在 JSON 位置收到意外令牌 o 1.
处理提交:
event.preventDefault();
fetch('http://localhost:3001/user/register',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:this.state
})
.then(data => data.json())
.then(data =>{
if(data.success) console.log('It works');
else console.log(data.info + data.success);
console.log(this.state);
});
还有我的apiapp.post:
app.post('/user/register', (req, res)=>{
res.setHeader('Content-Type', 'application/json');
console.log('Commiting to register');
console.log(req.body);
let user = new userModel({
firstName:req.body.firstName,
lastName:req.body.lastName,
age:req.body.age,
email:req.body.email,
username:req.body.username,
password:req.body.password
});
user.save()
.then((info)=>{
let data = {success:true, info:info};
res.send(data);
})
.catch((err)=>{
let data = {success:false, info:err};
res.send(data);
});
console.log('Registering processed');
})
您可以尝试使用 res.json(data)
而不是 res.send(data)
这会将您的响应内容类型设置为 application/json
在客户端,您还可以对从提取响应中收到的数据执行 JSON.parse(data)
。
长话短说,问题出在我发布的问题之上,我使用 express.json() 作为我需要的中间件,但我没有正确使用它。
使用 express.json() 作为中间件期望请求的主体是一个字符串,以便它可以将其转换为 json,所以在反应中我使用了 JSON.stringify(jsonObject ) 其中 jsonObject 是我需要的获取正文内容。
我正在尝试向我的 api 服务器发出 POST 获取请求以做出反应,无论我如何发送数据,我都会在 JSON 位置收到意外令牌 o 1.
处理提交:
event.preventDefault();
fetch('http://localhost:3001/user/register',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:this.state
})
.then(data => data.json())
.then(data =>{
if(data.success) console.log('It works');
else console.log(data.info + data.success);
console.log(this.state);
});
还有我的apiapp.post:
app.post('/user/register', (req, res)=>{
res.setHeader('Content-Type', 'application/json');
console.log('Commiting to register');
console.log(req.body);
let user = new userModel({
firstName:req.body.firstName,
lastName:req.body.lastName,
age:req.body.age,
email:req.body.email,
username:req.body.username,
password:req.body.password
});
user.save()
.then((info)=>{
let data = {success:true, info:info};
res.send(data);
})
.catch((err)=>{
let data = {success:false, info:err};
res.send(data);
});
console.log('Registering processed');
})
您可以尝试使用 res.json(data)
而不是 res.send(data)
这会将您的响应内容类型设置为 application/json
在客户端,您还可以对从提取响应中收到的数据执行 JSON.parse(data)
。
长话短说,问题出在我发布的问题之上,我使用 express.json() 作为我需要的中间件,但我没有正确使用它。 使用 express.json() 作为中间件期望请求的主体是一个字符串,以便它可以将其转换为 json,所以在反应中我使用了 JSON.stringify(jsonObject ) 其中 jsonObject 是我需要的获取正文内容。