javascript - 401 API Authentication Failed using POST 方法
问题描述
我正在实现一个基于 POST 方法的 API。现在,我已经尝试过 axios 以及 fetch (promise) 方法,但我经常遇到“401 Authentication Failed”的错误。
- 为了测试,我将要发送到 this.state 的数据值定义为默认值。
- apiKey和userId在 React.Component 之外定义为 var。
- 我没有使用内置的btoa功能,而是使用顶部导入的 npm 目录中的一个。
这是 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));
}
任何帮助表示赞赏。谢谢你。
解决方案
在请求的标头部分尝试在“基本”之后添加空格,应该如下所示:'''
const options = {
headers: {
"Authorization": "Basic " + btoa(userId+":"+apiKey),
"Content-Type":'application/json'
}
};
''' 因为身份验证标头首先需要授权类型,后跟空格,然后是 api 密钥
推荐阅读
- apache-flink - 如果不同的作业可以在同一个工人的不同分离进程上运行会更稳定吗?
- python - 生产服务器上的 Django 迁移问题
- javascript - 类型 'Observable<{}[]>' 不能转换为类型 'AngularFireList
' - amazon-web-services - EC2 公共 DNS 已更改,但 Nginx 反向代理仍然有效
- r - R Shiny Change Box 背景颜色
- sql - 当原因具有特殊字符和逗号的值时,选择查询返回 null
- css - 不透明度倾斜背景图像
- r - ggplot不尊重scale_fill_manual()中的颜色顺序?
- sql-server - SSIS 在不同服务器实例上的多个表之间加载数据
- javascript - 使用 for 和 case 循环在 google 表格和电子表格之间进行排序和移动