0

Related question.

I am trying to send a POST request to an API for testing purposes. I keep getting

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{my local IP}' is therefore not allowed access. The response had HTTP status code 403.

Here is the relevant code:

function searchSimilar2(){
var base_url = "{request url}"
var send_url = base_url + "{inline arguments}"
var params = '{"size":10, "mediaUrl":"https://cdn.yoox.biz/39/39706632kh_20_f.jpg2"}'

function func(){
    console.log(this.response)
}

var hReq = new XMLHttpRequest();
hReq.open('POST', send_url)
hReq.setRequestHeader('Content-Type', 'application/json')
hReq.onload = func;
hReq.send(params)

I omitted the request url and arguments, since I know the problem is not with them.

As per the linked questions answers, I am not using JQuery, and I am running a python SimpleHTTPServer where I am sending this request from. I keep getting this error.

Community
  • 1
  • 1
GreySage
  • 1,153
  • 19
  • 39
  • The server isn't sending back the required CORS headers. Are you loading your page via a `file://` URL? If so, the browser considers the page and the `http://localhost` server to be two different domains. – Pointy Feb 08 '17 at 22:55
  • Yes, I read that in the linked question. That is why I am running a simpleHTTPServer and opening the html file that runs the javascript from there. – GreySage Feb 08 '17 at 23:09
  • Understand that as far as the browser is concerned what has to match is the "http" part ("http" or "https"), the domain **letter for letter**, and the port number. They have to be the same when compared as a string, not just the same IP address. – Pointy Feb 09 '17 at 00:07
  • It's not completely clear what's going on. Is that ajax request happening from your browser, via the containing page? Or is it somehow running underneath Python in the server? – Pointy Feb 09 '17 at 00:09

2 Answers2

2

You will need to set an "Access-Control-Allow-Origin" header value on the SimpleHttpServer response. The header value will need to contain the hostname or IP of the requesting application. Alternatively, you can set the "*" wildcard value to allow all origins, but you should only do that if you actually want to allow all origins as it creates a bit of a XSS vulnerability:

//allow single origin
self.send_header('Access-Control-Allow-Origin', 'http://yourapp.com')
self.end_headers()

-OR-

//allow all origins
self.send_header('Access-Control-Allow-Origin', '*') 
self.end_headers()
JTW
  • 3,546
  • 8
  • 35
  • 49
-1

By changing the settings of the server, I got this to work.

Part of the url for the requests is "v1/api", and for some reason switching it to "api/v1" made everything work.

GreySage
  • 1,153
  • 19
  • 39