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

2

6

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.

Arnelle answered 1/10, 2015 at 3:54 Comment(1)
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 ShadowingFraser
P
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}));
    }
  });
});
Phonology answered 1/10, 2015 at 4:21 Comment(0)
P
1

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

Puddling answered 23/1, 2022 at 1:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.