如何组合ajax和CORS将json请求发送到另一个域

时间:2016-10-31 13:42:19

标签: javascript php jquery json ajax

我一直在尝试从另一个域托管的网络服务获取信息。最初我只使用了ajax,但后来我意识到这并不是出于安全原因。之后我了解到我可以使用CORS来解决这个问题,问题是我不能让它运转起来。任何sugestions?

的javascript:

$.ajax({
type: "POST",
    url: "http://localhost:34887//Login",
    data: '{"username":"Administrator","password":""}',
    dataType: "json",

    success: function(data) {
        alert(data[1]);
    },
    error: function(data){
        alert("fail");
    }
});

使用CORS的PHP代码:

header('Access-Control-Allow-Origin: http://localhost:34887/');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

我得到的错误:

XMLHttpRequest无法加载http://localhost:34887/Login。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://localhost:5050'因此不允许访问。响应的HTTP状态代码为500.

这与我不使用CORS时得到的错误相同。 (欢迎提供CORS的在线示例)

2 个答案:

答案 0 :(得分:2)

如果你有两台服务器 - Server A(让它为http://localhost:5050)和服务器B(让它为http://localhost:34887/),你试图从一个运行的网站运行ajax Server AServer B

Website on Server A ===AjaxRequest==> Server B

然后Server B应使用Server A标头Access-Control-Allow-Origin标题来回复Server A上运行的网站的请求:

header('Access-Control-Allow-Origin: Server A');

这是:

header('Access-Control-Allow-Origin: http://localhost:5050');

此代码应在Server B内投放,以接受来自Server A的请求。

答案 1 :(得分:0)

您可以将*添加到Access-Control-Allow-Origin,这样就可以了:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');