Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overcome CORS from Angular 2 to Node/express?

I have this code in my express application

var app = require('express')()
var bodyParser = require('body-parser')
var cors = require('cors')

app.use(bodyParser.urlencoded({ extended: true }))

app.post('/user', cors(), function (req, res) {
    res.send(req.body.username);
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

And this is my angular 2 function that sends the request

getData() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    let params = 'username=test';

    this.http.post('http://localhost:3000/user', params, {headers: headers})
        .map(res => res.json())
        .subscribe(data => {});
}

I get this error in console:

XMLHttpRequest cannot load http://localhost:3000/user. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

But when I send a request using jquery ajax, it's working without any errors.

like image 241
RezaT1994 Avatar asked Mar 09 '23 08:03

RezaT1994


1 Answers

You can enable CORS in nodejs/express with a code like this:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

So your code should look like this:

var app = require('express')()
var bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

app.post('/user', function (req, res) {
    res.send(req.body.username);
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})
like image 62
eko Avatar answered Mar 16 '23 01:03

eko