Javascript 类型错误:res.json 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42075746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: res.json is not a function
提问by boombamboo
I'm trying to send two json but It doesn't work. It prints TypeError: res.json is not a functionbut I don't get why It happens. Is there any ideas? Thank you !!
我正在尝试发送两个 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);
})
});
回答by tymeJV
Because you're overwriting your resvariable in the .thenof your rpfunction:
因为你在你的函数中覆盖了你的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")
回答by D Lowther
.jsonisn't a function. 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).
.json不是函数。除非您使用的库,使得它一个,JavaScript使用JSON(有两个方法.parse()和.stringify()其中一个在上面的行中使用)。
If you are trying to set an object property by the name of .jsonthen it would be:
如果您尝试通过名称设置对象属性,.json则它将是:
res.json = {data: [res, dangerRate]};
回答by shivam srivastava
With new httpClient libary, you don't need to call .json() method, Just use this simple map instead of the json method.
使用新的 httpClient 库,您不需要调用 .json() 方法,只需使用这个简单的映射而不是 json 方法。
.map(res => res );

