Node.js请求中的JSON和数据之间有什么区别?
我想知道节点HTTP请求中json
和data
之间的区别
var http = require('http');
let api = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
data:{
}
}
let apiTwo = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
json:{
}
}
http.request(api,function(err,resp,body){ // 400 for api and 200 for apiTwo
if(err){
console.log(err);
}
else{
console.log(resp);
console.log(body);
}
})
[当我在请求中以data
作为键访问上述API时,我得到了400
。当我用json
作为请求中的键击相同的API时,我得到的是200
。
总之,我的问题是在服务器上配置了此json
和data
吗?它们之间有什么区别?什么时候首选哪个?
当我们发出发布请求时,主体应为字符串格式。在您的第一个api请求中,主体是一个对象,但不是字符串,这就是为什么您得到400
尝试在下面传递数据,这里我使用json.strinfify对对象进行字符串化
let api = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
data:JSON.stringfy({})
}
在第二个API调用中,请求中没有正文,因此服务器会将正文视为null,因此它接受请求。您因此得到200,但不是因为JSON
Node.js请求中的JSON和数据之间有什么区别?
我想知道节点HTTP请求中json
和data
之间的区别
var http = require('http');
let api = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
data:{
}
}
let apiTwo = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
json:{
}
}
http.request(api,function(err,resp,body){ // 400 for api and 200 for apiTwo
if(err){
console.log(err);
}
else{
console.log(resp);
console.log(body);
}
})
[当我在请求中以data
作为键访问上述API时,我得到了400
。当我用json
作为请求中的键击相同的API时,我得到的是200
。
总之,我的问题是在服务器上配置了此json
和data
吗?它们之间有什么区别?什么时候首选哪个?
当我们发出发布请求时,主体应为字符串格式。在您的第一个api请求中,主体是一个对象,但不是字符串,这就是为什么您得到400
尝试在下面传递数据,这里我使用json.strinfify对对象进行字符串化
let api = {
url: "https://someurl/api/ticket/create",
method: "POST",
headers:
{
"cache-control": "no-cache",
"Content-Type": "application/json",
"Accept": "application/json"
},
data:JSON.stringfy({})
}
在第二个API调用中,请求中没有正文,因此服务器会将正文视为null,因此它接受请求。您因此得到200,但不是因为JSON