javascript Node.js - “TypeError - res.setHeader 不是函数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32879170/
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
Node.js - "TypeError - res.setHeader is not a function"
提问by accasio
I'm trying to load JSON from a URL to a variable and send it back to the client's javascript
我正在尝试将 JSON 从 URL 加载到变量并将其发送回客户端的 javascript
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, res){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: res.result}));
}
});
});
Every time I run the code the server says that res.setHeader
isn't a function and the rest breaks.
每次我运行代码时,服务器都会说这res.setHeader
不是一个函数,其余的就会中断。
回答by
Both post
and getJSON
callbacks have same res
variable name.
Try this:
无论post
和getJSON
回调有相同的res
变量名。试试这个:
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, response){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: response.result}));
}
});
});