dow46218 2013-06-14 17:27
浏览 66
已采纳

跨域AJAX withCredentials,PHP返回标题内容长度,但没有内容

I am trying to send a cross domain request from a page on one domain to a PHP server on an other domain. Everything works fine without credentials (I need session) but as soon as I add credentials, it don't work.

Here is the JS code :

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://phpserver.net',true);
xhr.withCredentials = true ;
xhr.onreadystatechange = function(e) {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
}
xhr.send();

Please remember that it works without credentials. Now there is no alert. So I inspected with Firebug the network :

The request is correctly handled by the server, it's received with an HTTP code 200 but there is no content. I checked the headers :

HTTP/1.1 200 OK

Date: Fri, 14 Jun 2013 17:20:19 GMT

Server: Apache/2.4.2 (Win64) PHP/5.4.3

X-Powered-By: PHP/5.4.3

Access-Control-Allow-Origin: *

access-control-allow-credentials: true

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Pragma: no-cache

Set-Cookie: key=441wqr3e4cf2456c763c1ea173aa06b5ad284e5f38; expires=Fri, 28-Jun-2013 17:20:19 GMT key2=248fbaf41cdd698549fdddb341927885; expires=Fri, 28-Jun-2013 17:20:19 GMT

Content-Length: 8

Keep-Alive: timeout=5, max=100

Connection: Keep-Alive

Content-Type: text/html; charset=UTF-8

And finally my strangest discovery : The header "Content-Length" actually shows the real content length ! If I add an echo "foo", the content-length increase by three and so on.

I looked trough lots of questions but this one is really tricky and I can't find any solution :(

EDIT : I forgot to mention that this request works if instead of the xmlHttpRequest object I use a user-script and the GM_xhr function.

  • 写回答

1条回答 默认 最新

  • doushi7761 2013-06-14 17:39
    关注

    When setting headerAccess-Control-Allow-Credentials to true, you cannot use a wildcard for header Access-Control-Allow-Origin. That is, a specific host must be specified.

    Instead of:

    Access-Control-Allow-Origin: *
    

    Use:

    Access-Control-Allow-Origin: http://safedomain.com
    

    You can even set the Access-Control-Allow-Origin header to the Origin header received in the request. Not sure about PHP, but using the Java Servlets API:

    String origin = request.getHeader("Origin");    
    request.setHeader("Access-Control-Allow-Origin", origin);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题