使用凭据获取Reactjs似乎不起作用

问题描述 投票:0回答:1

我正在尝试使用Bearer键进行GET请求,无法弄清楚为什么它不起作用。在Postman中,GET请求可以完美地工作,但是在我的React.js应用程序中无法实现。我在控制台日志中收到401未经授权的错误。

const token = 'https://eshop-deve.herokuapp.com/api/v2/orders/2117155815564'

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

关于任何问题的任何想法?

谢谢!

reactjs authorization fetch bearer-token
1个回答
0
投票

如果使用无心跳模式,浏览器将不会发送不在CORS安全列表中的标头。因此,“授权”标头将不会发送,服务器也不会接收它并响应401代码。

这里有更多详细信息。 Using fetch API with mode: 'no-cors', can’t set request headers

解决方案:删除模式:不使用cors,服务器将响应cors请求。或者只保留内容类型标题。

© www.soinside.com 2019 - 2024. All rights reserved.