1

I have a question about node js and the express framework.

I want to do the following in my server code:

  • Call remote server with xmlhttprequest 1
  • Process the response
  • Call remote server with xmlhttprequest 2

This is a simplified version of my server code:

app.js:

var express = require('express');
var routes = require('./routes');
var about = require('./routes/about');
var user = require('./routes/user');
var contact = require('./routes/contact')
var http = require('http');
var path = require('path');
var cors = require('cors');
var app = express();
....
app.get('/', routes.index);   //<---currently this is handled in index.js, in function index.

index.js:

exports.index = function(req, res){
 //xmlhttprequest 1    // <--- send xhr 1 
 //process data
 //xmlhttprequest 2    // <--- send xhr 2
};

I get the message Cant send headers after they are sent. I read the express documentation and gleaned that this happens when we try to modify the header after the request has been sent. I also read something about middleware, and routing. But the documentation is not clear to me.

Can someone point out what the ideal way to do this would be? I can work with links that have relevant information. I am new to express and node js.

Edit: More details:

  • The user is on the landing page of my website foo/.

  • He enters some details, based on which i make the first xmlhttprequest.

  • I process the data from API 1, use the processed data as input for API 2, which is again an xmlhttprequest.
K_U
  • 15,832
  • 8
  • 26
  • 29

1 Answers1

1

If you want to send two different XHR requests, you'll need to define two different routes for it:

app.get('/XHR1', routes.xhr1);
app.get('/XHR2', routes.xhr2);

The reason you're getting Can't send headers after they are sent is because you're responding to the client (probably through something like res.send(200), full list) and then trying to respond to the client again. You can only respond once per call.

Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • But what if i want the two xhr's to be sent as part of the same URL, without routing the user to two different URLs on the server? For example: app.get('/', routes.xhr1and2) – K_U May 18 '14 at 10:17
  • You'll need to provide more code - I don't quite understand what you're asking. – SomeKittens May 19 '14 at 03:36