1

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?

5
  • Check /handle_seeds is an available route or not in a flask, and check type also is it POST or not Commented Jun 7, 2019 at 4:53
  • yes it is. I've edited the question. Commented Jun 7, 2019 at 5:15
  • Can you console log in handleSubmit and check if its get's called or not? Commented Jun 7, 2019 at 6:00
  • how so? I've tried console.log(data) but page is imediately redireted to error thrown on browser, not on console. but I can see that is logging POST route not found Commented Jun 7, 2019 at 6:07
  • Please see my answer, that might be the cause. Commented Jun 7, 2019 at 6:25

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I get the same error. se my edit. I use a nginx reverse proxy for requests, and have included the route, still to no avail.
I don't have knowledge about reverse proxy; if answer not helping I will delete it then,
You dont have to. Reverse proxy is working with GET route; should work with POST as well
it is working now. I had to rebuild the containers in order to apply my nginx changes. thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.