reactjs - 使用 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)
});
解决方案
我这样使用它:
使用控制台日志检查您的 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
推荐阅读
- java - 如何从 sqlite 中删除未在列表中列出的键?
- swift - SwiftUI:如何更改 NavigationView.toolbar 背景颜色
- python - Python 全局计数
- python - 为什么通过除法而不是乘法来精确表示二进制?
- python - 从回调中打印会破坏模型打印的数据,拟合和数据值不同
- java - 如何处理 java.lang.IllegalArgumentException 以播放音频?
- node.js - 使用 Webpack/Babel 从 ES6 为 Node.js 生成 CommonJS 兼容包
- sql - PostgreSQL如何获取具有两个或多个满足相同条件的列的行
- go - 在 Golang (yaml) 中将特定结构解组为字符串
- cookies - ExpressionEngine 5 - Cookie 同意解决方案