【问题标题】:How to force axios GET request to send headers?如何强制 axios GET 请求发送标头?
【发布时间】:2019-10-21 06:02:14
【问题描述】:

尽管我的代码在 Vue 的一个组件中,但问题出在 Axios,让我解释一下原因。所以,我正在尝试获取一些信息,如下所示:

axios.get('http://localhost:8181/roles/1',  
  {
    headers: {
      'Api-Token': 'tokenTOKEN',
      'Content-Type': 'application/json'
    }
  }
)
.then(response => {console.log(response)})
.catch(response => {
  console.log(response);
})

所以,是的,我正确地导入了 Axios。是的,我知道我们不应该在 GET 请求中发送 Content-Type 标头。但是,我已经阅读了 RFC 7231,它并没有说不可能,只是不常见。所以,我们想在我的请求中发送一个 Content-Type 标头。

那么,我怎么知道它不起作用?嗯,我的 Lumen API 中的一个中间件是这样的:

<?php

namespace App\Http\Middleware;

use Closure;

class JsonVerifier
{
    public function handle($request, Closure $next)
    {
        if($request->isJson())
        {
            return $response = $next($request);
        }
        else
        {
            return response('Unauthorized.', 401);
        }
    }
}

我尝试使用 Postman 发送特定的 GET 请求,并且它有效。我尝试像这样使用fetch()

var miInit = { method: 'GET',
               headers: {
                 'Api-Token': 'tokenTOKEN',
                 'Content-Type': 'application/json'
             },
             mode: 'cors',
             cache: 'default' };

fetch('http://localhost:8181/roles/1',miInit)
.then(function(response) {
  console.log(response);
})

它有效!在这两种情况下(使用 Postman 和 fetch()),我的 API 都会返回所需数据。

但是,当我尝试使用 Axios 时,我收到带有“未经授权”字样的 401 响应,这意味着 Axios 没有正确发送标头。

现在,问题。有没有其他方法可以在 axios GET 请求中发送标头?无论fetch() 和 Postman 的情况如何,我如何强制 Axios 发送标头?

【问题讨论】:

  • 您正在发送一个 GET 请求。它永远不会 JSON。您是否考虑过 Accepts 标头和 $request-&gt;wantsJson() 函数,这实际上是针对这种情况的目的?
  • 你应该可以像 fetch 那样做... stackoverflow.com/a/47916965/10431732
  • @MattOestreich 不。 Axios(正确地)在Content-Type 标头和无数据请求(如GET 或空POST)的情况下防止这种情况发生。 github.com/axios/axios/blob/…
  • @ceejayoz - 啊,我读这个问题太快了 - 我认为它正在剥离所有标题......不过,这对我来说非常有意义!

标签: vue.js axios lumen


【解决方案1】:

如果您发送没有正文的请求,Axios 会自动 (as it should) 删除 Content-Type 标头,就像处理任何 GET 请求一样。

https://github.com/axios/axios/blob/2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644/lib/adapters/xhr.js#L112

// Add headers to the request
if ('setRequestHeader' in request) {
  utils.forEach(requestHeaders, function setRequestHeader(val, key) {
    if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
      // Remove Content-Type if data is undefined
      delete requestHeaders[key];
    } else {
      // Otherwise add header to the request
      request.setRequestHeader(key, val);
    }
  });
}

您可能正在寻找 Accepts 标头和 $request-&gt;wantsJson()(或 acceptsJson())。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2019-03-07
    • 2013-10-16
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多