javascript - Making a cross domain request with authentication header -
first of all, server (not mine) returns following headers:
access-control-allow-origin: * access-control-allow-credentials: true
i'm trying find out how pass request site authentication token. i'm running code on local apache server.
this code:
function get_data(){ var url = '$url'; var x = new xmlhttprequest(); x.open("get", url, true) if (x.readystate == 4 && x.status == 200) { var responsetext = x.responsetext; console.log(responsetext) }; x.setrequestheader("authentication", "bearer $token"); x.withcredentials = true x.send() }
the console returns:
xmlhttprequest cannot load $url. response preflight request doesn't pass access control check: no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost' therefore not allowed access. response had http status code 403.
while reading on documentation saw not allowed manually set headers. when removed x.setrequestheader("authentication", "bearer $token");
i did answer server (an authentication error, obviously.) how go adding information anyway request?
the headers returned server:
request url:$serverurl request method:options status code:403 forbidden remote address:$ipaddress response headers view source cache-control:no-cache connection:close content-type:text/html request headers view source accept:"*/*" accept-encoding:gzip, deflate, sdch accept-language:nl-nl,nl;q=0.8,en-us;q=0.6,en;q=0.4 access-control-request-headers:authentication access-control-request-method:get connection:keep-alive host:$host origin:http://localhost referer:http://localhost/mv.html user-agent:mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, gecko) chrome/47.0.2526.111 safari/537.36
before actual request, browser sends option request, check "options" has requesting (allowed methods, origins etc.).
check network tab options request (preflight) browser sends. request must have appropriate response headers e.g.
access-control-allow-origin: * access-control-allow-credentials: true access-control-allow-methods: post, get, options
see here: https://developer.mozilla.org/en-us/docs/web/http/access_control_cors#access-control-allow-methods
since server sends 403 status header options request, means server doesnt handle options request right, or sets 403 host measure of security. unless changed, there no way can access api via xhr.
Comments
Post a Comment