Node server not responding anything to POST request in cors mode with custom headers

I am using express js in backend and doing fetch in frontend. My frontend is hosted by webpack-dev-sever which is running locally on port 3000. My express js server is running locally on port 3001. I need to send some custom headers along-with my request.

My express js server is using 'morgan' for logging on terminal. The code of my server looks like this:

const express = require('express')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const fs = require('fs')
const path = require('path')
const mime = require('mime')
const http = require('http')
const cors = require('cors')

const server = express();

let whitelist = [
    'http://localhost:3000',
];
var corsOptions = {
    origin: function(origin, callback){
        var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
        callback(null, originIsWhitelisted);
    },
    credentials: true
};
server.use(cors(corsOptions));
server.use(bodyParser());
server.use(morgan('dev'));
server.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, x-imei, X-API-Key, requestId, Authorization');
  res.header('Access-Control-Allow-Methods', '*');
  next()
})

server.post('/verify/identifier', function(req, res, next) {
  console.log(req.body)
  console.log(req.headers)
  res.send({"responseCode":"0012"});
});

server.listen(port, function() {
  console.log(`server hosted on port ${port}`)
})

My frontend code is this:

export function fetchMerchantApi(url, body) {
  let reqObj = {
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": secret_key,
      "requestId": getUniqueId()
    },
    cache: 'default',
    mode: 'cors'
  }
  try {
    return new Promise((res, rej) => {
      fetch(url, reqObj).then(result => {
        return result.json()
      }).then(data => {
        res(data)
      });
    })
  } catch(e) {
    throw new Error(e);
  }
}

fetchMerchantApi("http://localhost:3001/verify/identifier", reqBody).then(res => {
console.log(res);
})

All imports, syntax, etc are correct.

The chrome debugger tool's network tab is this: network request details

The logs in terminal of server:

body

[0] { customField1: 'Y',

[0] imei: '358967064854480',

[0] isMerchantExist: 'Y',

[0] mobileNo: '9999999999',

[0] serialNumber: 'ZY22285JKV' }

headers:

[0] { host: 'localhost:3001',

[0] connection: 'keep-alive',

[0] 'content-length': '119',

[0] 'x-imei': '358967064854480',

[0] origin: 'http://localhost:3000',

[0] requestid: '9999999999300513303519185',

[0] 'content-type': 'application/json',

[0] 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36',

[0] 'x-api-key': 'l7xx5a9a4eea46054ef38b18b5e6fdbd2c5a',

[0] accept: '/',

[0] referer: 'http://localhost:3000/auth/verifyNo',

[0] 'accept-encoding': 'gzip, deflate, br',

[0] 'accept-language': 'en-IN,en-GB;q=0.8,en-US;q=0.6,en;q=0.4' }

morgain log:

[0] POST /cr/v2/merchant/verify/identifier 200 2.432 ms - 23

After all this, I am getting no error and also no response data from backend.

Funny thing is that my rest client(Postman) works fine. I get data on postman.

Upvotes: 1

Views: 766

Answers (1)

Naveen Kerati
Naveen Kerati

Reputation: 971

This is a tricky one . It is an options request, that is a preflight request from the browser. The options request contains two http headers Access-Control-Request-Headers' andAccess-Control-Method` . But it looks like you allowing every method in cors options.

you can enable pre flight requests like

app.options('*', cors())

Upvotes: 0

Related Questions