javascript - 使用 httpPost 的 422 响应返回 {"response":{}} instead of the actual API response

标签 javascript networking promise http-post es6-promise

如果我运行 curl localhost:4000/myserver,我得到: {错误:“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()为此。

下面是真实情况的示例(如果您从网络服务器接收数据,数据始终是字符串类型):

// 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);

关于javascript - 使用 httpPost 的 422 响应返回 {"response":{}} instead of the actual API response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616066/

相关文章:

python - Pygame 的基本网络

javascript - 运行一个 Promise.all 的 Promise.alls

javascript - 当数组中的所有项目都已处理完毕后调用done()

javascript - 我可以在 Node 的全局范围内覆盖 ES 6's Promise by bluebird' 的实现吗?

javascript - Highcharts 根据类别值更改栏背景颜色

javascript - 让 JS API 返回一个 polyfilled DOM 节点

javascript - 在拖动或调整大小时禁用或更改功能

php - 使用SOCKS代理在php中建立套接字连接

linux - 如何设计一个需要通过网络发送数据的守护服务?

javascript - 有没有办法在 SVG 中嵌入文本?