javascript - How to send POST request to Django API from ReactJS web app? - Stack Overflow

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

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:

  • ReactJS: /

  • Django Python API:

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;

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:

  • ReactJS: https://mherman/blog/dockerizing-a-react-app/

  • Django Python API: https://semaphoreci./munity/tutorials/dockerizing-a-python-django-web-application

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;
Share Improve this question edited Nov 2, 2018 at 17:16 user10367815 asked Nov 2, 2018 at 17:13 ScalaBoyScalaBoy 3,39214 gold badges52 silver badges96 bronze badges 1
  • 1 maybe something like this? techiediaries./react-ajax – erik258 Commented Nov 2, 2018 at 17:18
Add a ment  | 

1 Answer 1

Reset to default 3

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

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

In order to get info from the form, trigger onChange on each input, and save the input state to ponent 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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742387457a4434342.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信