TypeError: res.json 不是一个函数

新手上路,请多包涵

我正在尝试发送两个 json,但它不起作用。它打印 TypeError: res.json is not a function 但我不明白为什么会这样。有什么想法吗?谢谢 !!

 app.post('/danger', function response(req, res) {
    let placeId = req.body.data;
    let option = {
      uri: 'https://maps.googleapis.com/maps/api/directions/json?',
      qs: {
        origin:`place_id:${placeId[0]}`, destination: `place_id:${placeId[1]}`,
        language: 'en', mode: 'walking', alternatives: true, key: APIKey
      }
    };
    rp(option)
      .then(function(res) {
        let dangerRate = dangerTest(JSON.parse(res), riskGrid);
        res.json({ data: [res, dangerRate]});
      })
      .catch(function(err) {
        console.error("Failed to get JSON from Google API", err);
      })
});

原文由 boombamboo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 841
2 个回答

因为您要覆盖 res rp 函数中的 .then 变量:

 app.post('/danger', function response(req, res) { //see, "res" here was being overwritten
   ..
   ..
   rp(option).then(function(response) { //change the variable name of "res" to "response" (or "turtles", who cares, just dont overwrite your up most "res")

原文由 tymeJV 发布,翻译遵循 CC BY-SA 3.0 许可协议

我收到此错误消息是因为我在处理程序方法中的参数顺序错误。 (业余爱好者的错)

错误的顺序:(res,req)

 app.get('/json', (res, req) => {
  res.json({
    "message": "Hello json"
  });
});

正确的顺序:(req, res)

 app.get('/json', (req, res) => {
  res.json({
    "message": "Hello json"
  });
});

原文由 Fotis Kolytoumpas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题