我正在尝试使用不记名 key 执行 GET 请求,但不明白为什么它不起作用。
在 Postman 中,GET 请求完美地工作,但在我的 React.js 应用程序中却无法实现。我在控制台日志中收到 401 未经授权的错误。我添加了 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>
);
}
}
}
这就是对象应该的样子。 Postman GET response
这是我收到的控制台日志错误。 Console log errors
没有模式:'no-cors'
我遇到这个问题,我该如何解决它? Failed to fetch error
对于可能出现的问题有什么想法吗?
谢谢!
最佳答案
我可以通过简单地取出 mode: 'no-cors'
和 'Access-Control-Allow-Origin': '*'
来解决这个问题。所以在 fetch 中发送的对象最终会是这样的:
const obj = {
method: 'GET',
withCredentials: true,
headers: {
'Authorization': 'Bearer ' + key,
'Content-Type': 'application/json'
}
}
关于Reactjs 使用凭据获取似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61262904/