Angular will send an HTTP request using the OPTIONS method instead of POST

I am trying to send some HTTP requests from my angular.js application to my server, but I need to solve some cors errors.

An HTTP request equals this example:

functions.test = function(foo, bar) {
    return $http({
        method: 'POST',
        url: api_endpoint + 'test',
        headers: {
            'foo': 'value',
            'content-type': 'application/json'
        },
        data: {
            bar:'value'
        }
    });
};

the first attempt ends with an error of some errors. Therefore, I implemented the following lines in my php server script:

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');

The first error is now fixed.

Now the developer console (on Chrome) shows me the following errors:

angular.js: 12011 OPTIONS http: // localhost: 8000 / test (anonymous function)

423ef03a: 1 XMLHttpRequest cannot load http: // localhost: 8000 / test . Prepress response has invalid HTTP status code 400

and the network request looks as I expected (status 400 is also expected):

network request

, ( ), OPTIONS POST. , ?

+10
4

OPTIONS , (CORS). , , , . , HTTP 200 OK OPTIONS, "" , POST . , 2XX, "" .

:

  • HTTP, application/xml application/json ..
  • GET, HEAD POST, POST , application/x-www-form-urlencoded, multipart/form-data text/plain

, :

  • HTTP, .. 200 OK
  • Access-Control-Allow-Origin: * ( * , , , )

, CORS, :

  • HTTP- (.. 2XX)
  • HTTP- (, 200 OK), CORS (.. Access-Control-Allow-*)

, , , HTTP- 200 OK.

Mozilla Developer Network , , CORS HTML5Rocks.

+19

Angular 2, NODE API.

, Cross Origin Header, POST API Angular.

( NODE), , GET, PUT .

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');

Dawid Ferenczy post , PREFLIGHT , , NODE JS:

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

, PREFLIGHT ( 200, , groovy...), , , DB!

0

, cors, @CrossOrigin(origins = "*", maxAge = 3600) .

.

0

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 ");
exit;}

, .

0

Source: https://habr.com/ru/post/1660233/


All Articles