I have an Angular app (v1.13.15) and Express.js(v4.12.4) as backend.
I have a DELETE method in my backend, and I have enabled CORS support for it.
But, when I use Angular $http.delete, I run into this error
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried using Jquery, $.ajax() call for it, and I get the same problem!
I also tried using POSTMAN to do a DELETE request and there is no problem.
But, I have no problem accessing using my Angular for my GET and POST method..
May I know what is this problem?
My backend URL http://localhost:3000
I serving my AngularJS using gulp-webserver http://localhost:8000
My server code
exports.deleteGPSData = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
let id = req.params.id;
res.send('here');
}
and my Angular code
$http.delete(API_URL + '/gps/' + id)
.success(function(res) {
if (res.result !== 1) {
return defer.reject(new Error(id + ' failed to delete'));
}
defer.resolve(res.id);
})
.error(function(status) {
defer.reject(status);
});
I have no problem with GET and POST method! only when I use DELETE method, I ran into CORS errors!
I have attached a screenshot below for the request header using Google Chrome
Below is the screenshot from Postman,
I managed to solve this problem, it is due to preflight request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
When doing CORS for DELETE, it will first send an OPTIONS method to the server, and then it will resolve to DELETE method
So it in backend, I should have route for OPTIONS and then call next() to pass it to DELETE method
Backend code:
app.options('/gps/:id', routes.gps.optionGPSData);
app.delete('/gps/:id', routes.gps.deleteGPSData);
and my router middleware
exports.optionGPSData = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
next();
}
POSTMAN is able to perform a DELETE request? (this is because it sends a DELETE http request to my server, and not OPTIONS) whereas in web browser, it will send an OPTIONS for preflight request (this is mainly for security concern)
*shoutout to @FrankerZ, he enlights me to compare POSTMAN and my Chrome result, and then I see there is a difference in Access Control Allow Method, which leads me to try cors middleware (https://www.npmjs.com/package/cors), and it works and then I managed to pin the problem and is due to the preflight request!
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