Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js + express + cors not working: pending options requests

I tried about 10 different options but I cant get my POST request start working instead i have options request that is pending and never completes

server.js

var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');

var app = express();

app.use(cors());

var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Accept');

  // intercept OPTIONS method
  if ('OPTIONS' == req.method) {
      res.send(200);
  } else {
      next();
  }
};
app.use(allowCrossDomain);

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

app.use(require('./routes/order-templates.js'));
app.use(require('./routes/statuses.js'));
app.use(require('./routes/fields.js'));
app.use(require('./routes/users.js'));
app.use(require('./routes/groups.js'));
app.use(require('./routes/upload.js'));
app.use(require('./routes/feedback.js'));

app.use(require('./routes/order.js'));

app.use(express.static('public'));

var mongoDB = 'mongodb://localhost/ior';

mongoose.connect(mongoDB, {
  useMongoClient: true
});

app.get('*', function (request, response) {
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

app.listen(3000, function () {
  console.log('Fired at ' + Date());
});

users.js

var express = require('express');
var router = express.Router();

var User = require('../model/user.js');
var bodyParser = require('body-parser');

var app = express();

var cors = require('cors')

var corsOptions = {
    origin: 'http://188.225.82.166:3000/',
    optionsSuccessStatus: 200 
}

app.use(cors())
app.use(bodyParser.json());

app.options('/users/auth/', cors(corsOptions))
app.post('/users/auth/', cors(), function (req, res, next) {
    User.findOne({"mail": req.body.mail, "password": req.body.password}, function (err, user) {
        if (err) throw err;
        if (user == undefined) {
            res.send({"result": "error" })
            res.sendStatus(200)
        } else {
            res.send({"result": "ok", "_id": user._id, "type": user.type })
        }
    });
})

module.exports = app

If I do

app.use(cors());

app.use(function(req, res, next) {
    console.log('After CORS ' + req.method + ' ' + req.url);
    next();
});

in server.js I get

After CORS GET /
After CORS GET /bundle.js
After CORS GET /bootstrap.css.map
After CORS GET /favicon.ico

And nothing prints in console after post requests is triggered. Also worth mentioning the fact, that the problem exists only when I deploy to server with ubuntu. Locally on mac os machine everything is fine

like image 282
Alexey K Avatar asked Dec 24 '22 13:12

Alexey K


1 Answers

You should use cors before bodyParser and allow it for PUT/DELETE also.

// Add cors
app.use(cors());
app.options('*', cors());  // enable pre-flight
app.use(bodyParser.json());
like image 122
Abhyudit Jain Avatar answered Dec 28 '22 11:12

Abhyudit Jain