在HTTP请求中包含应导致域更改的标头字段

时间:2017-09-04 06:50:18

标签: javascript html rest http api-design

我有一个基于标题字段验证请求的API,然后返回一个HTML页面。

此API的请求必须以某种方式进行,以便域名从domain1.com更改为domain2.com (就像点击超文本一样)。< / p>

我无法使用<a>Link</a>因为我需要添加标题字段。 并且ajax无法使用,因为它不会将控件从domain1.com更改为domain2.com

这样的事情根本没有意义......

$.ajax({
 // Use ajax to authenticate
 ...
 success : function(path){

     // Load the path for domain change
     location.assign(path);      
     // Even this request should have a header field
 },
 ...    
})

我需要在单个请求中使用两者的功能(更改域和标头用法) - 如果可能,或至少需要2个请求。

有任何想法吗?

1 个答案:

答案 0 :(得分:0)

为了在标头中发送带有凭证的HTTP请求,并在成功时发送“更改域”,您可以使用带有302代码和Location的JSON响应 - 只是一个约定,浏览器行为不会被触发。

示例回复:

HTTP response code: 200 OK

HTTP response body:
{
  status: 302,
  location: 'domain2.com/result'
}

Ajax代码如下所示:

$.ajax({
  // Use ajax to authenticate, with credential in HTTP header
  ...
  success: function(result){
    if (result.status === 302) {
      window.location = result.location;
    }
  },
  ...    
})

将使用2个HTTP请求。一个用于Ajax,另一个用于重定向。