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:
when change post put, i'm sending options call instead put. , content-type switches content-type
.
my request payload send object:
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:
what does, is:
- checking request gonna made
- if it's post, put or delete
- it sends first option request check if domain, request sent, same 1 server.
- 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:
- i sent access-control-header
- what solved first 2 lines, and
- access-control-allow-origin specific subdomain port
best website find learn more cors.
Comments
Post a Comment