6

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;
ScalaBoy
  • 3,254
  • 13
  • 46
  • 84

1 Answers1

3

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();

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Sebastijan Dumančić
  • 1,165
  • 1
  • 11
  • 20
  • 1
    Thanks. I tried this approach, but got error: `Access to fetch at 'http://localhost:8000/' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.` – ScalaBoy Nov 02 '18 at 18:41
  • This is a Django related issue, not React. CORS, or `Cross origin resource sharing` is a security feature which blocks some unauthorized request. In order to solve it, you must add allow header to the Django API and authorize the domain from which you are triggering the request. In this case probably `localhost`or any other if it's a remote domain. – Sebastijan Dumančić Nov 02 '18 at 18:46
  • @ScalaBoy You need to allow `Cross Origin Resource Sharing` on your API (Django in your case) – Shivam Nov 02 '18 at 18:46
  • How do I solve it? I followed this approach, but still the code fails with CORS error https://github.com/crs4/ome_seadragon/wiki/Enable-Django-CORS-(Cross-Origin-Resource-Sharing)-Headers-configuration. and this: https://stackoverflow.com/questions/35760943/how-can-i-enable-cors-on-django-rest-framework – ScalaBoy Nov 02 '18 at 18:57
  • It's a completely different question, try asking it on Django subforums, I haven't been working with Django directly. – Sebastijan Dumančić Nov 03 '18 at 08:31
  • install django-cors-headers from pip and add it to installed apps after which you must add cors whitelist to settings.py, in the whitelist you have to add the locahost:3000 to whitelist it and allow it to make post request – ryonistic May 14 '22 at 02:25