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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:51:11  来源:igfitidea点击:

Node.js - "TypeError - res.setHeader is not a function"

javascriptnode.jsexpressgetjson

提问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.setHeaderisn't a function and the rest breaks.

每次我运行代码时,服务器都会说这res.setHeader不是一个函数,其余的就会中断。

回答by

Both postand getJSONcallbacks have same resvariable name. Try this:

无论postgetJSON回调有相同的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}));
    }
  });
});