[英]What is the difference between node.js https request and XMLHttpRequest?
[英]What is the difference between JSON and data in Node.js request?
我想知道json
和节点 HTTP 请求中的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
是在服务器上配置的吗? 它们之间有什么区别? 什么时候首选?
当我们发出 post 请求时,body 应该是字符串格式。 在您的第一个 api 请求中,正文是 object 但不是字符串,这就是您获得 400 的原因
尝试下面传递数据,这里我使用 json.strinfify 对 object 进行字符串化
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
我知道,经过大量搜索,API在服务器端分别处理data
和json
。 因此,当您在 API 请求中传递json
或data
时,go 通过 API 文档在json
之间data
正确选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.