reactjs - 使用 React JS 将数据发布到 API
问题描述
我是 React 的新手,并试图将数据发布到某些 API,但我无法做到这一点。这是我尝试过的方式
import React, { Component } from "react";
class Apinew extends Component {
constructor() {
super();
this.state = {
id: '',
name: '',
quote: '',
created_on: ''
};
}
change = e => {
this.setState({
[e.target.name]: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
console.log(this.state);
fetch('someAPI', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: {
id: this.id.value,
text: this.quote.value,
author: this.name.value,
created_on: this.createdOn.value
}
});
};
render() {
return (
<div>
<form>
<input
name="id"
ref={ref => {
this.id = ref;
}}
placeholder="Enter ID"
value={this.state.id}
onChange={e => this.change(e)}
/>
<br />
<input
name="name"
ref={ref => {
this.name = ref;
}}
placeholder="Enter Name"
value={this.state.name}
onChange={e => this.change(e)}
/>
<br />
<input
name="quote"
ref={ref => {
this.quote = ref;
}}
placeholder="Enter Quote"
value={this.state.quote}
onChange={e => this.change(e)}
/>
<br />
<input
name="created_on"
ref={ref => {
this.createdOn = ref;
}}
placeholder="Created On"
value={this.state.created_on}
onChange={e => this.change(e)}
/>
<br />
<button onClick={e => this.onSubmit(e)}>Submit</button>
</form>
</div>
);
}
}
export default Apinew;
我收到了这个错误:
选项 someAPI 405(不允许的方法)
无法加载某些 API:预检响应具有无效的 HTTP 状态代码 405。
Uncaught (in promise) TypeError: Failed to fetch
问题是什么?我应该怎么办?
谢谢
解决方案
首先,您应该了解405 错误意味着:
超文本传输协议 (HTTP) 405 Method Not Allowed 响应状态码表示请求方法为服务器所知,但已被禁用,无法使用。
您的 fetch 调用可能没有任何问题,但是您必须查看 api 要求,也许您缺乏权限,但很可能该方法是私有的,因此无法使用。
推荐阅读
- typescript - Typescript Class - 构造函数中应该有一个私有字段吗?
- mongodb - 根据地图值更新 mongo 文档并删除该值
- matlab - 从另一个文件夹将 Simulink 模型打开到内存中
- python - python:如何解释切片的索引
- python - 为什么当我输入另一个型号(如 Model X)时,这个程序只会显示 Model S 的总价格?
- google-sheets - 谷歌表格 5000 万个单元格计数工作
- html - 在 Next.js 中,如何创建一个覆盖整个浏览器窗口的 bg 图像
- docker - Docker 无法启动守护进程:未安装设备 cgroup [Debian GNU/Linux 9 (stretch)] armv7l
- azure-functions - 从只能访问有限虚拟网络的 Azure 存储帐户订阅事件的方法是什么?
- firebase - 我可以将我的 Firebase 存储设置在与我的 Firestore 和云功能不同的区域吗?