XHR POST无法发送凭据和标头

时间:2016-10-20 15:37:49

标签: javascript rest web xmlhttprequest fetch

我遇到一个奇怪的问题,我希望有一个非常简单的解决方案。我正在尝试向服务器发送POST请求。我尝试使用fetch并使用XMLHttpRequest没有运气。我的xhr请求如下所示:

var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(obj));

我的抓取请求如下所示:

fetch(location, {
      credentials: 'include',
      method: 'post',
      body: JSON.stringify({obj}),
      headers: {
        'Content-Type': 'application/json'
    })
    .then((response) => {
      if (response.ok){
        response = response.json();
      } else {
        response = {};
      }
      window.console.debug(response);
    })
    .then((json) =>{
      window.console.debug(json);
    })
    .catch((error) => {
      window.console.debug(error);
    });

这两者都有相同的结果。如果我像上面那样离开它,凭据就不会被发送,所以它会发送一个OPTIONS请求,我得到一个401.我的Chrome网络选项卡请求邮件的标题如下:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.146.101:8005
Origin:http://localhost:8555
Referer:http://localhost:8555/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36

如果我删除标题行,内容类型是错误的类型(显然),所以我得到415.铬网络标签请求标题消息如下所示:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Authorization:Basic YWRtaW46YWRtaW4=
Connection:keep-alive
Content-Length:504
Content-Type:text/plain;charset=UTF-8
Host:192.168.146.101:8005
Origin:http://localhost:8555
Referer:http://localhost:8555/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36

出于某种原因,当我添加标题时,它会删除凭据。我已经尝试发送编码用户:传入标题也是这样(但显然是真实的用户名/密码):

var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa('user:pass');
xhr.send(JSON.stringify(obj));

所有浏览器都会发生这种情况。 感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我相信我已经发现了这个问题。问题实际上是响应REST API的服务器被设置为对通过的所有内容进行身份验证,包括OPTIONS请求。 OPTIONS请求仅在我们尝试执行此跨源时创建,我就是这样。浏览器似乎从OPTIONS请求中删除了身份验证,并且由于我尝试命中的服务器验证OPTIONS请求(由于某些未知原因),因此它失败了。所以我现在尝试使用WAR代码并将其托管在同一台服务器上,并且我能够解决身份验证问题。

答案 1 :(得分:0)

withCredentials attibute仅指示是否应使用凭据进行跨站点访问控制请求,我不确定这是否是您正在寻找的内容 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

你试过这个吗?

var xhr = new XMLHttpRequest();
xhr.open("POST", location);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(user+':'+pass);
xhr.send(JSON.stringify(obj));
相关问题