【问题标题】:What is the difference between JSON and data in Node.js request?Node.js 请求中的 JSON 和数据有什么区别?
【发布时间】:2019-10-11 11:13:06
【问题描述】:

我想知道节点HTTP请求中jsondata的区别

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

简而言之,我的问题是这个jsondata是在服务器上配置的吗?它们之间有什么区别?什么时候首选?

【问题讨论】:

  • Neither of the two is documentented 所以我很困惑为什么它们甚至会影响事物。
  • 我也很困惑:)
  • 你能添加需求行吗? (例如const http = require('http');)(如果您使用一些库,我们知道。)
  • 已经有需求行,我没有添加有问题的
  • 我已将其添加到问题中。

标签: javascript node.js json http request


【解决方案1】:

当我们发出一个 post 请求时,body 应该是字符串格式。 在您的第一个 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

【讨论】:

  • 仍然是 400。我认为正文不应该是字符串,因为在标题中我指定了 Content-Type: application/json
【解决方案2】:

我知道,经过大量搜索,API 是在服务器端分别处理datajson 的。因此,当您在 API 请求中传递 jsondata 时,请查看 API 文档以在 jsondata 之间做出正确选择。

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2016-03-02
    • 1970-01-01
    • 2019-07-07
    • 2019-12-06
    • 1970-01-01
    • 2021-06-23
    • 2020-09-16
    • 1970-01-01
    相关资源
    最近更新 更多