如何强制axios GET请求发送headers?

How to force axios GET request to send headers?

尽管我的代码在 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 header。但是,我已经阅读了 RFC 7231,它并没有说不可能,只是不常见。所以,我们想在我的请求中发送一个 Content-Type header。

那么,我怎么知道它不起作用?好吧,我的 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 returns 期望数据。

然而,当我尝试使用 Axios 时,我收到了带有 "Unauthorized" 字样的 401 响应,这意味着 Axios 没有正确发送 header。

现在,问题。还有其他方法可以在 axios GET 请求中发送 headers 吗?我如何强制 Axios 发送 headers 而不管 fetch() 和 Postman 的情况如何?

如果您发送的请求没有 body,Axios 会自动 (as it should) 删除 Content-Type header,就像您处理任何 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 header 和 $request->wantsJson()(或 acceptsJson())。