HTTP request from Angular sent as OPTIONS instead of POST

前端 未结 5 682
孤街浪徒
孤街浪徒 2020-12-03 04:59

I\'m trying to send some HTTP requests from my angular.js application to my server, but I need to solve some CORS errors.

The HTTP request is made using the followin

5条回答
  •  情歌与酒
    2020-12-03 05:20

    I ran into a very similar problem writing an Angular 2 app - that uses a NODE server for the API.

    Since I am developing on my local machine, I kept getting Cross Origin Header problems, when I would try to POST to the API from my Angular app.

    Setting the Headers (in the node server) as below worked for GET requests, but my PUT requests kept posting empty objects to the database.

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, 
    Origin, Authorization, Accept, Client-Security-Token, Accept-
    Encoding, X-Auth-Token, content-type');
    

    After reading Dawid Ferenczy's post, I realized that the PREFLIGHT request was sending blank data to my server, and that's why my DB entries were empty, so I added this line in the NODE JS server:

      if (req.method == "OPTIONS")
        {
            res.writeHead(200, {"Content-Type": "application/json"});
            res.end();
        }
    

    So now my server ignores the PREFLIGHT request, (and returns status 200, to let the browser know everything is groovy...) and that way, the real request can go through and I get real data posted to my DB!

提交回复
热议问题