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.
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!')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With