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 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.
via WithoutBrain1994
No comments:
Post a Comment