简体   繁体   English

"Node.js - “TypeError - res.setHeader 不是函数”"

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

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不是一个函数,其余的都会中断。

Both post and getJSON callbacks have same res variable name. postgetJSON回调都具有相同的res变量名称。 Try this: 尝试这个:

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

for me this was happening when fetching data in a forum i built.对我来说,这是在我建立的论坛中获取数据时发生的。 i found the fix to this in this blogpost: https://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9我在这篇博文中找到了解决方法: https ://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9

i added code according to atul singh in the comments.我根据 atul singh 在评论中添加了代码。

changes in app.js app.js 的变化

app.use((res, next) => {
  ....
});

to

app.use((req, res, next) => {
  ....
});

now the app doesnt crash and it sucessfully fetches and displays the data现在应用程序不会崩溃,它会成功获取并显示数据

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

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