-1

I am trying to submit a form and send the form data to a flask server from React. It seems like POST is working fine. However, when I try to access to the form in the flask server, it returns ImmutableMultiDict([]).

Here are my codes:
register.js

async function sendUserInfo(userInfo) {
  await fetch('http://127.0.0.1:5000/get_user_info', {
    method: 'POST',
    body: userInfo
  })
  .then((response) => response.json())
  .then((response) => console.log(response))
}

async function handleSubmit(event) {
  event.preventDefault()
  await sendUserInfo(event.target);
}

//component function
function Register() {
  console.log('Register Page')

  return (
    <div id='main_container'>
      <form onSubmit={handleSubmit}>
        <input name='username' className='register_input' placeholder={inputUsername.placeholder}></input>
        <input name='gender' className='register_input' placeholder={inputGender.placeholder}></input>
        <input name='age' className='register_input' placeholder={inputAge.placeholder}></input>
        <select className="register_input">
          {cities.map((city) => {return <option className='select_option'value={city}>{city}</option>})}
        </select>
        <button className='input_button' >채팅 시작하기...</button>
        <input className='input_button' type='submit'></input>
      </form>
    </div>
  )
}

server.py

from chat_app.chat import ChatApp, ChatRoom, User
from flask import Flask
from flask import request
from flask_cors import CORS
import json

server = Flask(__name__)
CORS(server)

@server.route('/get_user_info', methods=['GET', 'POST'])
def get_user_info():
    user_info = request.form
    print(user_info)

    return json.dumps({'status': 'successful'})

server.run(debug=True)

I successfully get {'status': 'successful'} on the client side. But when I try to print out request.form, it returns ImmutableMultiDict([]).

I know that this question might be a duplicate but I am asking this question because I've been trying to fix it by referring to various posts in Stack Overflow or Google that deal with similar issues and I have failed.

davidism
  • 121,510
  • 29
  • 395
  • 339
gtj520
  • 196
  • 1
  • 10

2 Answers2

0

Flask's request.form will display the key-value pairs from the request (form-data generally). For more info, check out this excellent answer: https://stackoverflow.com/a/16664376/21330452.
In your case, the body contains a single serialized DOM node: from userInfo, and since this isn't in a key-value format, it won't appear in request.form, but the JSON {'status': 'successful'} will still be returned.

bleuatb
  • 184
  • 4
0

I have found the solution myself.

You can't simply transfer raw form and view it in the Flask server. Before transferring, you have to create a FormData instance. Then, you have to append the values of the inputs to the FormData instance. Finally, when you send the FormData instance via fetch, you can view it in the Flask server!

Here is my modified code:
register.js

async function sendFormData(formData) {
  await fetch('http://127.0.0.1:5000/get_user_info', {
    method: 'POST',
    body: formData
  })
  .then((response) => response.json())
  .then((response) => console.log(response))
}

async function handleSubmit(event) {
  event.preventDefault();

  const form = event.target;
  const username = form.username.value;
  const gender = form.gender.value;
  const age = form.age.value;
  const city = form.city.value;

  let formData = new FormData()
  formData.append('username', username)
  formData.append('gender', gender)
  formData.append('age', age)
  formData.append('username', username)

  await sendFormData(formData);
}
gtj520
  • 196
  • 1
  • 10