Why is same origin policy kicking in when making r

2019-01-20 00:41发布

I'm keeping the backend API as a separate project from the frontend HTML5 app consuming it. I'm using Yeoman for the frontend development. Yeoman runs on localhost:3501 and the backend on localhost:3000. When I make the API request from the browser (using AngularJS's $http), I hit the same origin policy:

XMLHttpRequest cannot load http://localhost:3000/venues. Origin http://localhost:3501 is not allowed by Access-Control-Allow-Origin.

AFAIK, same origin policy should kick in only when making request across different domains. Why is it whining when we do a request from localhost to localhost (albeit to different port)?

How can I make this work and will this cause problems in production?

2条回答
放荡不羁爱自由
2楼-- · 2019-01-20 01:35

The ports also count for cross domain requests, therefore http://localhost:3000 and http://localhost:3501 are 2 different domains (from browser's point of view).

If you need both applications (client and backend) to run on different ports, consider using http://enable-cors.org/

查看更多
放我归山
3楼-- · 2019-01-20 01:40

According to W3C, "An origin is defined by the scheme, host, and port of a URL", so the different port is causing your problems.

Two possible solutions:

  • CORS (Cross Origin Resource Sharing)
  • Using JSONP requests

Both would require changes to your backend (I'm not familiar enough wo. CORS would probably mean the least changes to your frontend (I think AngularJS supports it out-of-the-box).

查看更多
登录 后发表回答