首页 > 解决方案 > 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'我得到这个问题,我该如何解决?获取错误失败

关于可能是什么问题的任何想法?

谢谢!

标签: reactjsauthorizationfetchbearer-token

解决方案


我可以通过简单地取出mode: 'no-cors'and来解决它'Access-Control-Allow-Origin': '*'。所以在 fetch 中发送的对象最终会是这样的:

const obj = {
  method: 'GET',
  withCredentials: true,
  headers: {
    'Authorization': 'Bearer ' + key,
    'Content-Type': 'application/json'
  }
}

推荐阅读