8-Bit Borges
8-Bit Borges

Reputation: 10043

React frontend cannot POST to Flask backend

I am building a RESTful Flask application using React. I am trying to:

  1. render my Jinja2 templates via React component

  2. post data from React component back to Flask, server side


I'm using Axios for requests. This is the code I have so far:

import React, { Component } from 'react';
//import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
//from 'react-html-parser';
import axios from 'axios';


class Seeds extends Component{
  constructor (props) {
    super(props);
    this.state = {
      email: '',
      id: '',
      username: '',
      active: '',
      admin: '',
      template:'',
      input:''    
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  };
  componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getSeeds();
    }
  };
  getSeeds(event) {
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    };
    return axios(options)
    .then((res) => {
      console.log(res.data.data)
      this.setState({
        template: res.data.data[0].content
      })
    })    
    .catch((error) => { console.log(error); });
  };
  handleChange(event){
        this.setState({ input: event.target.value });
    }
  handleSubmit(event) {
    event.preventDefault();
    const data = {
      input: this.state.input,
    };

    const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_seeds`;
    axios.post(url, data)
      .then((res) => {
        console.log(data);
      })
      .catch((err) => {
      });
    };

    render(){

        //var seeds_page = this.state.template;
        var __html = this.state.template;
        var template = { __html: __html };

        return (
            <div dangerouslySetInnerHTML={template}/>
        );
    }
}

export default Seeds;

Templates are rendered and I GET data with this configuration, but I'm lost as to how POST data do backend from the rendered <forms>.

I have tried:

render(){
    var __html = this.state.template;
    var template = { __html: __html };

    return (
         <div id="parent">
           <div dangerouslySetInnerHTML={template}/>
            <form onSubmit={this.handleSubmit}>
             <input type='text' name='name' onChange={this.handleChange}/><br/>
             <input type='submit' value='Submit'/>
            </form>
        </div>
    );
}

Flask route:

@seeds_bp.route('/handle_seeds', methods=['GET','POST'])
def handle_seeds():

  user = User.query.filter_by(id=1).first()

  if request.method == 'POST':
    if 'input' in request.form:
        inp = request.form['input']
        user.input = inp
        db.session.commit()

        return redirect(url_for('seeds.seeds'))

A Nginx reverse proxy is being used for my Docker services (front and backend), and I've added to dev.conf:

  location /handle_seeds {
    proxy_pass        http://web:5000;
    proxy_redirect    default;
    proxy_set_header  Upgrade $http_upgrade;
    proxy_set_header  Connection "upgrade";
    proxy_set_header  Host $host;
    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Host $server_name;
  }

but I simply get at the browser:

Cannot POST /handle_seeds

How can I resolve this error?

Upvotes: 1

Views: 685

Answers (1)

Amol B Jamkar
Amol B Jamkar

Reputation: 1257

As per your code, when you click submit button, its submitting form with browser submit action,

So it's hitting the browser base_url/handle_seeds, that's why it's throwing this error,

Use this code, it should work.

 <div id="parent">
           <div dangerouslySetInnerHTML={template}/>
            <form>
             <input type='text' name='name' onChange={this.handleChange}/><br/>
             <button type="button" onClick={this.handleSubmit} />
           </form>
 </div>

Upvotes: 1

Related Questions