weixin_33670786 2017-03-15 04:07 采纳率: 0%
浏览 1180

CORS错误-我的标题

I have attempted to do my homework before asking this question but I cannot see what is missing in my headers.

I set the following headers in the javascript:

xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Access-Control-Allow-Origin');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST');
xhr.setRequestHeader('Content-Type', 'application/json');

The server sends the headers with the response:

Pragma: no-cache
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: PUT, GET, POST, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Max-Age: 86400
Transfer-Encoding: chunked
Cache-Control: no-store, must-revalidate, no-cache, post-check=0, pre-check=0
Date: Wed, 15 Mar 2017 03:39:49 GMT
Set-Cookie: PHPSESSID=1ng3l10lvrrovlmdbij5chv2f5; path=/
Server: Apache
Content-Type: application/json
Expires: Thu, 19 Nov 1981 08:52:00 GMT

Yet I get the error in my browsers(FF & Chrome):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.mydomain.com/login. (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

Can anyone see what I am missing?

  • 写回答

1条回答 默认 最新

  • weixin_33725807 2017-03-17 03:14
    关注

    This solution seems to work well.

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
        }
        exit;
    }
    
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    

    Javascript:

    xhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
    xhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
    xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
    xhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名