Alexey K
Alexey K

Reputation: 6723

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

Upvotes: 5

Views: 16332

Answers (6)

gwest7
gwest7

Reputation: 1653

Get rid of the trailing slash in origin.

Upvotes: 1

Rishab Surana
Rishab Surana

Reputation: 2167

After applying "cors" middleware. You should append "http://" before "localhost:". in URL

axios.get("http://localhost:8080/api/getData")
.then(function (response) {
this.items= response.data;
}).catch(function (error) {
console.log(error)
});

Upvotes: 0

Almas Kamitov
Almas Kamitov

Reputation: 103

It may be helpful for others like me: In the beginning I thougth it is the server side problem, but then the reason of cors error became my frontend. I was sending requests to localhost:3000/api instead of http://localhost:3000/api That's it

Upvotes: 6

BlueP
BlueP

Reputation: 607

For others like me scratching head for 2hrs trying to fix the POST cors issue, please also double check the options of your POST request.

For me it was a small typo of header: {...} instead of header(s): {...} in the POST options, the express server configured using cors allowing all origins responded with "Access-Control-Allow-Origin" restricted error.

Upvotes: 1

Abhyudit Jain
Abhyudit Jain

Reputation: 3748

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());

Upvotes: 8

parth
parth

Reputation: 674

Try this. In you user.js file use router.post instead of app.post.

router.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 })
        }
    });
})

Then export router module

module.exports = router;

Also i would suggest to use bodyparser in server.js file. So you don't need to use it in every file.

Upvotes: 0

Related Questions