【问题标题】:Node, express and Request on placeholder displaying lots on \n占位符上的节点、快递和请求在 \n 上显示批次
【发布时间】:2019-06-09 13:46:48
【问题描述】:

我正在使用 Node 和 Express 和 request.js 从 json 占位符获取数据。

代码如下:

...
import request from 'request';

const app = express();

app.get('/users', (req, res) => {
    request('https://jsonplaceholder.typicode.com/users', (error, response, body) => {
        res.json(body)
    });
});

app.listen(3000, () => {
 console.log("Server running on port 3000");
});

问题是我得到了很多 \n 例如:

"[\n  {\n    \"id\": 1,\n    \"name\": \"Leanne Graham\",\n    \"username\": \"Bret\",\n   etc

我怎样才能在没有额外内容的情况下获得干净的 json 格式?

【问题讨论】:

  • 有 Github 仓库吗?

标签: javascript node.js json express request


【解决方案1】:

res.json() 调用 JSON.stringify() 将对象转换为 string。使用 res.send() 发送 JSON。

【讨论】:

    【解决方案2】:

    只需添加json 选项来解析占位符的响应,然后再将其发送给客户端:

    app.get('/users', (req, res) => {
        request({
          url: 'https://jsonplaceholder.typicode.com/users'
          json: true // this option parses the response's body as JSON
        }, (error, response, body) => {
            res.json(body)
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2015-08-15
      • 2018-08-08
      • 1970-01-01
      • 2019-04-04
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      相关资源
      最近更新 更多