【问题标题】:Reactjs fetch with credentials doesn't seem to workReactjs 使用凭据获取似乎不起作用
【发布时间】:2020-07-30 10:33:38
【问题描述】:

我正在尝试使用 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>
      );
    }
  }
}

这就是对象的外观。 Postman GET response

这是我得到的控制台日志错误。 Console log errors

如果没有mode: 'no-cors' 我会遇到这个问题,我该如何解决? Failed to fetch error

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

谢谢!

【问题讨论】:

标签: reactjs authorization fetch bearer-token


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用 no-cors 模式,浏览器将不会发送不在 CORS 安全列表中的标头。所以不会发送“授权”头,服务器也不会收到并响应401码。

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

    解决方案:移除模式:no-cors,服务器响应cors请求。或者只保留内容类型标题。

    【讨论】:

    • 问题是如果我不使用no-cors 模式会出现Failed to fetch 错误,或者我该如何解决?
    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    相关资源
    最近更新 更多