第一种方式:
前端
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
$.post('/test', JSON.stringify({
"Email": "sfpe@163.com",
"Password": "123456",
"person": {
"age": 25
}
}), function(data){
debugger
});
后端
console.log(util.inspect({a: req.body}));
console.log(util.inspect({a: req.body.Email}));
结果
{ a:
{ Email: 'sfpe@163.com',
Password: '123456',
person: { age: 25 } } }
{ a: 'sfpe@163.com' }
第二种方式
前端
$.post('/test', {
post:JSON.stringify({
"Email": "sfpe@163.com",
"Password": "123456",
"person": {
"age": 25
}
})
}, function(data){
debugger
});
后端
console.log(util.inspect({a: req.body.post}));
console.log(util.inspect({a: req.body.post.Email}));
结果
{ a: '{"Email":"sfpe@163.com","Password":"123456","person": {"age":25}}' }
{ a: undefined }
问题:哪种传给后端的是json格式 ? 我用第二种传了,后端说不是json的格式....用第一种,报了这种错误: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我现在都不知道是我的问题 还是后端的问题。
Cross-domain request processing
The first one is OK, but it is cross-domain. You can look at building public APIs and CORS
Let me briefly explain why the console reported an error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
is because, in the
POST
method, theheader
incontent-type
is not any ofapplication/x-www-form-urlencoded,multipart/form-data
,multipart/form-data
, andtext/plain
. What you set isapplication/json; charset=utf-8
, which means that this request is a "complex" request. Then when the complex request faces cross-domain access, the backend service will be requested to provide corresponding support. For details, please refer to the document I posted, which contains the chapter "Not That Simple Request". It's best to take your back-end colleagues to read it together, lest they don't support you and you have to do it yourself for a long time. It’s useless