首页 > 解决方案 > 401 API Authentication Failed using POST 方法

问题描述

我正在实现一个基于 POST 方法的 API。现在,我已经尝试过 axios 以及 fetch (promise) 方法,但我经常遇到“401 Authentication Failed”的错误。

这是 React 组件代码:-

constructor(props) {
    super(props);

    this.state = {
      day: 1,
      month: 2,
      year: 2019,
      hours: 12,
      minutes: 59,
      tzone: 5.5,
      lat: 19.22,
      lon: 25.2
    };
  }

  componentDidMount() {

      const options = {
      headers: {
        "Authorization": "Basic" + btoa(userId+":"+apiKey),
        "Content-Type":'application/json'
      }
    };

      const url = `https://json.astrologyapi.com/v1/current_vdasha`
      const data = this.state

      fetch(url, { method: 'POST', 
        body: JSON.stringify(data), 
        headers: options })
        .then(res => res.json())
        .catch(error => console.error('error ---', error.message))
        .then(response => console.log('Success:', response));
  }

任何帮助表示赞赏。谢谢你。

标签: javascriptreactjsapipostxmlhttprequest

解决方案


在请求的标头部分尝试在“基本”之后添加空格,应该如下所示:'''

const options = {
headers: {
    "Authorization": "Basic " + btoa(userId+":"+apiKey),
    "Content-Type":'application/json'
  }
};

''' 因为身份验证标头首先需要授权类型,后跟空格,然后是 api 密钥


推荐阅读