通过获取获取数据有效,但无法与axios一起使用 [英] getting data with fetch is working but not with axios
问题描述
我可以通过获取获取数据
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/zh-CN/docs/Web/HTTP/CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
这篇关于通过获取获取数据有效,但无法与axios一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!