首页 > 解决方案 > 使用 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

问题是什么?我应该怎么办?

谢谢

标签: reactjsapipost

解决方案


首先,您应该了解405 错误意味着

超文本传输​​协议 (HTTP) 405 Method Not Allowed 响应状态码表示请求方法为服务器所知,但已被禁用,无法使用。

您的 fetch 调用可能没有任何问题,但是您必须查看 api 要求,也许您缺乏权限,但很可能该方法是私有的,因此无法使用。


推荐阅读