K_U
K_U

Reputation: 17802

How can I send multiple XMLHttpRequests

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

I want to do the following in my server code:

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:

Upvotes: 1

Views: 591

Answers (1)

SomeKittens
SomeKittens

Reputation: 39522

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.

Upvotes: 1

Related Questions