How to send POST request to Django API from ReactJS web app?

Question:

I created a very simple Django API. It returns a fixed numeric value (just for testing purpose):

views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse(0)

I also have a simple front-end developed using React JS. To develop the backend and front-end, I was using these two tutorials:

Now I want to send a POST request to Django API from ReactJS and pass name and email parameters. How can I do it?

This is my App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fullname: "",
      emailaddress: ""
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log(this.state);
  }

  render() {
    return (
      <div className="App">
        <header>
          <div className="container">
            <nav className="navbar">
              <div className="navbar-brand">
                <span className="navbar-item">Forms in React</span>
              </div>
            </nav>
          </div>
        </header>
        <div className="container">
          <div className="columns">
            <div className="column is-9">
              <form className="form" onSubmit={this.handleSubmit}>
                <div className="field">
                  <label className="label">Name</label>
                  <div className="control">
                    <input
                      className="input"
                      type="text"
                      name="fullname"
                      value={this.state.fullname}
                      onChange={this.handleChange}
                    />
                  </div>
                </div>

                <div className="field">
                  <label className="label">Email</label>
                  <div className="control">
                    <input
                      className="input"
                      type="email"
                      name="emailaddress"
                      value={this.state.emailaddress}
                      onChange={this.handleChange}
                    />
                  </div>
                </div>

                <div className="field">
                  <div className="control">
                    <input
                      type="submit"
                      value="Submit"
                      className="button is-primary"
                    />
                  </div>
                </div>
              </form>
            </div>
            <div className="column is-3">
              <pre>
                <code>
                  <p>Full Name: {this.state.fullname}</p>
                  <p>Email Address: {this.state.emailaddress}</p>
                </code>
              </pre>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;
Asked By: ScalaBoy

||

Answers:

To send HTTP requests from React app, you have two main options.

Either use integrated Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or something like axios (https://github.com/axios/axios).

In order to get info from the form, trigger onChange on each input, and save the input state to component state.

onChange = (prop: any, value: string) => {
  this.setState({
    [prop]: value
  });
};

After that, here’s an example using fetch API:

const response = fetch("endpoint_url", {
  method: 'POST',
  body: JSON.stringify({
    this.state.name,
    this.state.email
    // Other body stuff
  }),
  headers: {
    'X-Api-Key': API_KEY,
    'Content-Type': 'application/json'
    // Other possible headers
  }
});

And in the end you need to parse the response as JSON using const responseJson = response.json();

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.