使用 fetch 获取数据有效,但不能使用 axios [英] getting data with fetch is working but not with axios
问题描述
我可以通过 fetch 获取我的数据
I can get my data with 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 代码
but fetching data is not working with axios. this is my axios code
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)
});
推荐答案
我是这样使用的:
使用控制台日志检查您的标头对象是否处于良好状态.
Check if your headers object is in good shape with a console log.
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(跨源资源共享):
If the error you are getting is about CORS (Cross Origin Resource Sharing):
如果您想允许凭据,那么您的 Access-Control-Allow-Origin
不得使用 *
.您必须指定确切的协议、域、端口.
If you want to allow credentials then your Access-Control-Allow-Origin
must not use *
. You will have to specify the exact protocol, domain, port.
您需要将服务器设置为允许您的来源.
You need to set the server to allow your origin.
这是一个非常普遍的问题,您会经常看到它发生.在此处阅读有关 cors 的更多信息:
It's a very common problem and you will see it happen often. Read more about cors here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
这篇关于使用 fetch 获取数据有效,但不能使用 axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!