Reputation:
I'm trying to send JSON from two urls to one webpage(one that I am creating). It works perfectly when I send one request, but as soon as I add another request it sends an error saying "Can't set headers after they are sent:.
app.get("/service", function(req, res) {
request("http://example.com", function(error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
res.render("example.ejs", { data: data });
}
})
request("http://123.com", function(error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
res.render("example.ejs", { data: data });
}
})
});
Upvotes: 0
Views: 2590
Reputation: 4700
This error happens because you render example.ejs
twice this not allowed. I will show you two ways to achieve your goal without any error.
1) This way is a best practice.
// Install request-promise package first using this command below:
npm install request-promise;
// then replace your code with this one below:
app.get("/service", function(req, res) {
var request = require('request-promise');
var data1;
request("http://example.com")
.then(function(data) {
data1 = JSON.parse(data);
return request("http://123.com");
})
.then(function(data) {
data2 = JSON.parse(data);
console.log('data1', data1, 'data2', data2);
res.render("example.ejs", { data1: data1, data2: data2 });
});
});
and second way:
2) This way is bad practice avoid to use callback inside callback, but anyway it works.
app.get("/service", function(req, res) {
request("http://example.com", function(error, response, body) {
if (!error && response.statusCode == 200) {
var data1 = JSON.parse(body);
request("http://123.com", function(error, response, body) {
if (!error && response.statusCode == 200) {
var data2 = JSON.parse(body);
console.log('data1', data1, 'data2', data2);
res.render("example.ejs", { data1: data1, data2: data2 });
}
});
}
});
});
Summary: I suggest you to use 1 way, read this article about promises: https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/ and write clean code. I simply explain that promises are tool to avoid callback inside callback.
Upvotes: 1