简体   繁体   English

类型错误:res.json 不是函数

[英]TypeError: res.json is not a function

I'm trying to send two json but It doesn't work.我正在尝试发送两个 json,但它不起作用。 It prints TypeError: res.json is not a function but I don't get why It happens.它打印TypeError: res.json is not a function但我不明白为什么会发生。 Is there any ideas?有什么想法吗? Thank you !!谢谢 !!

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

Because you're overwriting your res variable in the .then of your rp function:因为您在rp函数的.then中覆盖了res变量:

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")

I got this error message because I had the arguments in the wrong order in the handler method.我收到此错误消息是因为我在处理程序方法中的参数顺序错误。 (amateur's fault) (业余的错)

Wrong order: (res, req)错误的顺序:(res,req)

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

Right order: (req, res)正确的顺序:(req, res)

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

.json isn't a function. .json不是函数。 Unless you are using a library that makes it one, JavaScript uses JSON (with two methods .parse() and .stringify() one of which you use in the line above).除非您使用的库使其成为一体,否则 JavaScript 使用JSON (有两种方法.parse().stringify() ,您在上面一行中使用了其中一种)。

If you are trying to set an object property by the name of .json then it would be:如果您尝试通过.json的名称设置对象属性,那么它将是:

res.json = {data: [res, dangerRate]};

使用新的 httpClient 库,您不需要调用 .json() 方法,只需使用这个简单的映射而不是 json 方法。

.map(res => res );

In your case, you write res in nested but if you write a response(res,req) then also get the same error.在您的情况下,您在嵌套中编写 res 但如果您编写 response(res,req) 也会得到相同的错误。

So make sure check the sequence所以一定要检查顺序

check the sequence=>检查顺序=>

If you have write nested res and you write (res,req) you get error.如果你写了嵌套的 res 并且你写了 (res,req) 你会得到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM