首页 > 解决方案 > 使用 fetch 获取数据有效,但不适用于 axios

问题描述

我可以通过 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)
            });

标签: reactjsfetchaxios

解决方案


我这样使用它:

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

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


推荐阅读