Origin is not allowed by Access-Control-Allow-Orig

2018-12-31 00:32发布

I'm making an Ajax.request to a remote PHP server in a Sencha Touch 2 application (wrapped in PhoneGap).

The response from the server is the following:

XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

How can I fix this problem?

22条回答
公子世无双
2楼-- · 2018-12-31 00:43

If you don't have control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security.

Note that I wouldn't use this for normal "web surfing". For reference, see this post: Disable same origin policy in Chrome.

One you use Phonegap to actually build the application and load it onto the device, this won't be an issue.

查看更多
只靠听说
3楼-- · 2018-12-31 00:43

If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:

<system.webServer>
  ...

    <httpProtocol>
        <customHeaders>
            <!-- Enable Cross Domain AJAX calls -->
            <remove name="Access-Control-Allow-Origin" />
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>
查看更多
高级女魔头
4楼-- · 2018-12-31 00:44

In Ruby on Rails, you can do in a controller:

headers['Access-Control-Allow-Origin'] = '*'
查看更多
深知你不懂我心
5楼-- · 2018-12-31 00:44

In Ruby Sinatra

response['Access-Control-Allow-Origin'] = '*' 

for everyone or

response['Access-Control-Allow-Origin'] = 'http://yourdomain.name' 
查看更多
与风俱净
6楼-- · 2018-12-31 00:44

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);
查看更多
与君花间醉酒
7楼-- · 2018-12-31 00:44

The wildcard isn't a very safe option. You'd want it to be more specific - checkout the answer I've written here on the same question; how to bypass Access-Control-Allow-Origin?

查看更多
登录 后发表回答