shaan
shaan

Reputation: 524

Express middleware is executing twice if headers are passed with request?

Hi I'm newbie in Node js I'm using express framework for this

My middleware is running twice if I'm passing headers to it below is my set-up

const express = require('express');
const port = 3003;
const app = express();


app.use( function(req, res, next){
    console.log('This is called twice when headers are passed in request:');
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    next();
});


app.get('/', function(req, res, next){
    console.log('hey im called');
    res.send({message: 'hi'})
});


const server = app.listen(port, function(error){
    if (error){
    console.log(`Error: ${error}`)
    return
    }
    console.log(`server is listining on ${port}, ${this}`)
});

call from browser console $.ajax({ url: 'http://localhost:3003', headers: { x: 1 , y: 1}})

Upvotes: 0

Views: 359

Answers (1)

faizulhaque
faizulhaque

Reputation: 106

Seems like you are making AJAX call from a different domain than localhost:3003 browser will first send the pre-flight option call, before the actual API.

You can find more details on pre-flight or CORS Here

Solution: You can render the html page on root url / which will contain the ajax call and place your existing api route as

app.get('/test', function(req, res, next){ console.log('hey im called'); res.send({message: 'hi'}) });

and your ajax call would be

$.ajax({ url: 'http://localhost:3003/test', headers: { x: 1 , y: 1}})

Upvotes: 1

Related Questions