mare
mare

Reputation: 89

Post data to API with React JS

I am new at React and trying to post data to some API but I can't manage to do that. This is the way I tried

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;

and I am getting this error:

OPTIONS someAPI 405 (Method Not Allowed)

Failed to load someAPI: Response for preflight has invalid HTTP status code 405.

Uncaught (in promise) TypeError: Failed to fetch

What is the problem? What should I do?

Thanks

Upvotes: 1

Views: 1784

Answers (1)

Fabien Greard
Fabien Greard

Reputation: 1894

First you should understand that 405 error means :

The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response status code indicates that the request method is known by the server but has been disabled and cannot be used.

There is probably nothing wrong with your fetch call, however you must look at the api requirement, maybe you lack of permissions but it is most likely the method is private and thus cannot be used.

Upvotes: 2

Related Questions