javascript - Angular $http is sending OPTIONS instead of PUT/POST -


i trying update/insert data in mysql database through php backend. i'm building front end angularjs , using $http service communicating rest api.

my setup looks this:

i'm setting header via $httpprovider:

 $httpprovider.defaults.withcredentials = true;  $httpprovider.defaults.headers = {'content-type': 'application/json;charset=utf-8'}; 

and post-call looks this:

   return $http({       url: url,       method: "post",       data: campaign     }); 

the dev console in chrome shows me this:

enter image description here

when change post put, i'm sending options call instead put. , content-type switches content-type.

my request payload send object:

enter image description here

how set header properly?


edit:

the php backend sets headers:

   $e->getresponse()               ->getheaders()               ->addheaderline('access-control-allow-methods', 'get, post, put, delete, options');     $e->getresponse()               ->getheaders()               ->addheaderline('access-control-allow-origin', '*'); 

is there missing?

ok, i've solved it.

what problem?
cors workflow delete, put , post follows:

enter image description here

what does, is:

  1. checking request gonna made
  2. if it's post, put or delete
  3. it sends first option request check if domain, request sent, same 1 server.
  4. if not, wants access-header allowed send request

important here: options request doesn't send credentials.

so backend server disallowed put request.

solution:
putting inside .htaccess file

rewritecond %{request_method} options rewriterule ^(.*)$ blank.php [qsa,l] header set access-control-allow-origin "http://sub.domain:3000" header set access-control-allow-credentials "true" header set access-control-max-age "1000" header set access-control-allow-headers "x-requested-with, content-type, origin, authorization, accept, client-security-token, accept-encoding" header set access-control-allow-methods "post, get, options, delete, put" 

after this, create empty .php file called blank.php inside public folder.

edit: 1 commenter pointed out, instead of creating empty php file, can add rewrite rule .htaccess file\;

rewriterule ^(.*)$ $1 [r=200,l,e=http_origin:%{http:origin}]] 

to clarify:

  1. i sent access-control-header
  2. what solved first 2 lines, and
  3. access-control-allow-origin specific subdomain port

best website find learn more cors.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -