问题
I'm trying to send two json but It doesn't work. It prints TypeError: res.json is not a function but I don't get why It happens. 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);
})
});
回答1:
Because you're overwriting your res variable in the .then of your rp function:
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")
回答2:
.json isn'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).
If you are trying to set an object property by the name of .json then it would be:
res.json = {data: [res, dangerRate]};
回答3:
With new httpClient libary, you don't need to call .json() method, Just use this simple map instead of the json method.
.map(res => res );
来源:https://stackoverflow.com/questions/42075746/typeerror-res-json-is-not-a-function