I have an angular 2 app which should authenticate to a Node Express backend where it sends an login request to the backend and receives a cookie. It should send this cookie
I had your situation. With Maciej answer I solved my problem.
I added the { withCredentials: true }
to my request options that already had the headers.
Then server-side, on my express base file server.js
, i added
var cors = require("cors");
var corsSettings = {
origin: true,
methods: ['POST'],
credentials: true
};
app.use(cors(corsSettings));
I actually excluded the Access-Control-Allow-Origin:*
, so my only header (server-side) is
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, access-control-allow-origin, access-control-allow-headers");
next();
});
Just wanna point out that as Maciej mentioned, you need some body in your request. So even if your query doesn't need it you need to call it with an empty body string.
const jsonHeads = new Headers();
jsonHeads.append('Content-Type', 'application/x-www-form-urlencoded');
jsonHeads.append('Access-Control-Allow-Origin', '*');
jsonHeads.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, access-control-allow-origin');
options = { headers : myHeaders, withCredentials: true }
this.http.post('http://myApi:8080/list', '', options);
This way, angular started sending cookies and authenticating properly. I hope this helps. I needed this myself a couple of hours ago.
By default angular is not sending cookies. Try pass { withCredentials: true }
to your RequestOptions:
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post(this.connectUrl, <stringified_data> , options);