最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

I'm trying to load JSON from a URL to a variable and send it back to the client's 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.

I'm trying to load JSON from a URL to a variable and send it back to the client's 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.

Share Improve this question asked Oct 1, 2015 at 3:54 accasioaccasio 1851 gold badge3 silver badges12 bronze badges 1
  • 2 You have multiple variables with the same name -- res. Having the same name, it's not possible to refer to both at once (res.setHeader() vs. res.result). Though, renaming one of them, even slightly, should make them both accessible. Ref: Variable Shadowing – Jonathan Lonowski Commented Oct 1, 2015 at 4:11
Add a comment  | 

2 Answers 2

Reset to default 11

Both post and getJSON callbacks have same res variable name. 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

i added code according to atul singh in the comments.

changes in 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

发布评论

评论列表(0)

  1. 暂无评论