【问题标题】:422 response using httpPost gives back {"response":{}} instead of the actual API response使用 httpPost 的 422 响应返回 {"response":{}} 而不是实际的 API 响应
【发布时间】:2018-10-02 20:39:09
【问题描述】:

如果我运行 curl localhost:4000/myserver,我会得到: {error: "foo"}

//MyAPI
function create(){
 return httpPost('localhost:4000/myserver', myParams);
}

并调用它:

return MyApi.create(config, params).then(res => {
    console.log("Full success" + JSON.stringify(res));
  })
  .catch(err => {
    console.log("Full error" + JSON.stringify(err));
  })

控制台日志只显示Full error{"response":{}},与我的cURL不匹配。

如何获得完整的错误和响应正文?

【问题讨论】:

  • 你的意思是JSON.parse,而不是JSON.stringify

标签: javascript networking promise http-post es6-promise


【解决方案1】:

当您使用异步调用时,在大多数情况下(如果您的框架没有自动执行此操作),您必须解析响应以获取可以进一步使用的数据,为此请使用 JSON.parse()

这是一个实际发生的例子(如果您从网络服务器接收数据,则数据始终是 string 类型):

// Fake response
const response = '{ "name":"John", "age":30, "city":"New York"}';
console.log('typeof response:', typeof response);

// Parsing the response
const parsed = JSON.parse(response);
console.log('typeof parsed:', typeof parsed);
console.log('parsed:', parsed);

【讨论】:

    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多