TypeError:res.json不是函数

boo*_*boo 6 javascript json node.js express

我正在尝试发送两个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);
      })
});
Run Code Online (Sandbox Code Playgroud)

tym*_*eJV 19

因为你在你的函数中覆盖你的res变量:.thenrp

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")
Run Code Online (Sandbox Code Playgroud)


Fot*_*pas 18

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

错误的顺序:(res,req)

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

正确的顺序:(req, res)

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