【问题标题】:getting data with fetch is working but not with axios使用 fetch 获取数据有效,但不适用于 axios
【发布时间】:2019-05-29 08:42:25
【问题描述】:

我可以通过 fetch 获取我的数据

 let myHeaders = new Headers();
        myHeaders.append('X-Auth-Token', token,);
        myHeaders.append('Content-Type', 'application/json');      
            fetch("myUrl", {
            withCredentials: true,
            headers: myHeaders
            }).then(function (response) {
                console.log(response)
            })

但在 axios 上无法获取数据。这是我的 axios 代码

  const headers={
            'X-Auth-Token': token,
            "content-type":"application/json"
        }
        axios.get('myUrl',{headers:headers,withCredentials:true})
            .then(response => {
                console.log(response)
            })
            .catch(err => {
                console.log(err)
            });

【问题讨论】:

  • 不工作是什么意思?请显示错误
  • (这是错误)。当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

标签: reactjs fetch axios


【解决方案1】:

我是这样用的:

使用控制台日志检查您的标头对象是否处于良好状态。

const headers = {
        'X-Auth-Token': token,
        'content-type': 'application/json'
    };
console.log(headers);
const request = axios.create({
    myUrl,
    headers: myHeaders,
    withCredentials: true
})


request.get() // If you add a string inside the brackets it gets appended to your url
    .then(res => console.log(res))
    .catch(err => console.log(err))

如果您遇到的错误是关于 CORS(跨源资源共享):

如果您想允许凭据,则您的 Access-Control-Allow-Origin 不得使用 *。您必须指定确切的协议、域、端口。

您需要将服务器设置为允许您的来源。

这是一个非常常见的问题,您会经常看到它发生。在此处阅读有关 cors 的更多信息:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

【讨论】:

  • 标头正常,但仍然出现拒绝访问错误
  • 好的,所以您的问题似乎出在 CORS 中。我更新了答案。
猜你喜欢
  • 2018-06-22
  • 2020-11-19
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2019-09-09
  • 2020-03-16
  • 2020-06-13
相关资源
最近更新 更多