I’m trying to load JSON from a URL to a variable and send it back to the client’s javascript
JavaScript
x
16
16
1
var getJSON =require('get-json');
2
3
app.post('/json', function(req, res) {
4
getJSON(url, function(err, res){
5
if(err)
6
{
7
console.log(err);
8
}
9
else
10
{
11
res.setHeader('content-type', 'application/json');
12
res.send(JSON.stringify({json: res.result}));
13
}
14
});
15
});
16
Every time I run the code the server says that res.setHeader
isn’t a function and the rest breaks.
Advertisement
Answer
Both post
and getJSON
callbacks have same res
variable name.
Try this:
JavaScript
1
16
16
1
var getJSON =require('get-json');
2
3
app.post('/json', function(req, res) {
4
getJSON(url, function(err, response){
5
if(err)
6
{
7
console.log(err);
8
}
9
else
10
{
11
res.setHeader('content-type', 'application/json');
12
res.send(JSON.stringify({json: response.result}));
13
}
14
});
15
});
16