Home > Mobile >  Data posted to flask endpoint from JS not processed in endpoint
Data posted to flask endpoint from JS not processed in endpoint

Time:05-07

I have written a simple todo app with react acting as a frontend and flask handling CRUD from a DB. The app is using axios to handle the requests; GET completes fine however when attempting to POST JSON the flask api returns a 400 error. Here's some condensed sample code.

JS POST function.

  function testPost(){

    axios.post('http://' window.location.hostname ':8000/todo/', {
      title: "test123",
    }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })

  }

Serverside

class Todo(Resource):
    def post(self): # create a new todo
        conn = pool.getconn()
        cur = conn.cursor()

        app.logger.info(request.form['title'])

        cur.execute("INSERT INTO todo (task, done) VALUES (%s, %s)", (request.form['title'], False))
        conn.commit()
        app.logger.error(e)
        cur.close()
        pool.putconn(conn)

Other methods not shown

Then the rest of the server code attaching the resource to the api and the CORS setup (not shown in file order)

app = Flask(__name__)
CORS(app, methods=['POST','GET','PUT','DELETE'])
api = Api(app)


api.add_resource(Todo, '/todo/')

app.run(debug = True, host='0.0.0.0', port=port)

Tests

Using python to test the api works fine, running this in a seperate python file will add to the DB.

response = requests.post(URL   "todo/", data={"title": f"test{randint(1, 100)}"})

My best guess is that axios is not adding the data to the request in a way that the backend is unable to process. Before using axios I tried to make the request with XMLHttprequest however this presented the same problem. I swapped to axios on the recommendation of someone else, given its alleged improved simplicity.

CodePudding user response:

request.form['key'] and request.get_json()['key'] are completely different fields python requests in the way I used it posts to the former and js posts to the latter. Modifying the function to use whichever is available fixes this.

  • Related