I want to know about the difference between json
and data
in node HTTP requests
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);
}
})
When I hit the above API with data
as key in the request, I get 400
. When I hit the same API with json
as key in request I am getting 200
.
In short, my question is this json
and data
are configured on the server? What is the difference between them? Which one is preferred when?
when we make a post request then the body should be in string format. in your first api request the body is an object but not string, that is why you are getting 400
Try bellow to pass data, here I am using json.strinfify to stringify the 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({})
}
In second API call there is no body present in the request so the server will consider body as null so it accepts the request. You are getting 200 because of this but not because of JSON
I got to know that after searching a lot, APIs are handled on the server-side for data
and json
separately. So when you pass json
or data
in your API request, go through the documentation of APIs for the right choice between json
or data
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.