reactjs - Reactjs 使用凭据获取似乎不起作用
问题描述
我正在尝试使用 Bearer 密钥发出 GET 请求,但不知道为什么它不起作用。在 Postman 中,GET 请求完美运行,但在我的 React.js 应用程序中无法实现。我在控制台日志中收到 401 Unauthorized 错误。我添加了mode: 'no-cors'
,否则我有一个Failed to fetch
错误。
const token = 'https://website.com'
const key = 'XXXXXXXXXXXXX'
const obj = {
method: 'GET',
mode: 'no-cors',
withCredentials: true,
headers: {
'Authorization': 'Bearer ' + key,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
orders: []
};
}
componentDidMount() {
fetch(token, obj)
.then(res => res.json())
.then(
(result) => {
console.log(result)
this.setState({
isLoaded: true,
orders: result.order
});
},
(error) => {
console.error(error)
this.setState({
isLoaded: true,
error
});
}
)
}
render () {
const { error, isLoaded, orders } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
{orders.order.number}
</div>
);
}
}
}
这就是对象的外观。 邮递员 GET 响应
这是我得到的控制台日志错误。控制台日志错误
没有mode: 'no-cors'
我得到这个问题,我该如何解决?获取错误失败
关于可能是什么问题的任何想法?
谢谢!
解决方案
我可以通过简单地取出mode: 'no-cors'
and来解决它'Access-Control-Allow-Origin': '*'
。所以在 fetch 中发送的对象最终会是这样的:
const obj = {
method: 'GET',
withCredentials: true,
headers: {
'Authorization': 'Bearer ' + key,
'Content-Type': 'application/json'
}
}
推荐阅读
- javascript - 如何打破 XSS 的双引号?
- java - 将 Steam 响应转换为 java graphql API 中 DatafetcherResult 对象的一部分
- ansible-inventory - 一个密码失败时的ansible库存尝试不同
- ios - TextField 在其他视图中通过协议更改值,如果用户更改 textField 输入如何存储值
- react-native - React Native Fetch data from api issue
- node.js - heroku push 卡住了
- powershell - 我正在做 3 个连续的 foreach 循环,它花费了很多时间?有没有更好的方法来解决这个难题?
- javascript - 使用 Express 异步错误的 Stange 行为
- javascript - JavaScript/DOM:MutationObserver 检测 DOM 树中任何位置的 `lang` 属性的变化
- unit-testing - 如何在 test.check 中生成随机电子邮件地址?