简体   繁体   English

将表单数据从React句柄提交功能发送到python API?

[英]Post form data from React handle submit function to python API?

I'm extremely new to React and Python and just trying to do a simple post from a react form to my Python API that will interface with a mongoDB. 我是React和Python的新手,只是尝试从react表单到将与mongoDB接口的Python API做一个简单的文章。 I have a form in react that invokes a handleSubmit function on submit. 我在react中有一个表单在提交时调用handleSubmit函数。 I want the handleSubmit function to POST to my Python API running on port 5000. My react app is running on port 8080. 我希望handleSubmit函数能够发布到端口5000上运行的Python API。我的react应用程序正在端口8080上运行。

The handleSubmit looks like this: handleSubmit看起来像这样:

handleSubmit(event) {
    const axios = require('axios');
    const baseUrl = 'http://localhost:5000'

    axios.post('http://localhost:5000/api/create', JSON.stringify(params))
        .end((error, response) => {
            if (!error && response) {
                console.log('got a valid response from the server')
            } else {
                console.log(`Error fetching data from the server: `, error)
            }
        });

    event.preventDefault();
}

Python endpoint code: Python端点代码:

@app.route('/api/create', methods=['POST'])
def create(self):
    if request.method == 'POST':
        print(request.args.get('exp_title'))
        return True
    return False

When I click the button, my python API endpoint isn't reached because react is trying to post to a route on port 8080. What am I missing? 当我单击按钮时,我的python API端点未到达,因为react试图发布到端口8080上的路由。我缺少什么?

I've tried using a regular ajax call and get the same result. 我尝试使用常规的ajax调用并获得相同的结果。 At one point, I did something and got a CORS error in the browser, but I can't remember how I did that. 有一次,我做了一些事情,在浏览器中遇到了一个CORS错误,但是我不记得我是怎么做到的。

To enable cors, you need to install pip install -U flask-cors, here is the website: https://flask-cors.readthedocs.io/en/latest/ or you can define cors in proxy in your reactjs package.json like here: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development 要启用cors,您需要安装pip install -U flask-cors,这是网站: https ://flask-cors.readthedocs.io/en/latest/,或者您可以在reactjs package.json中的代理中定义cors。就像这里: https : //facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

Once you install cors in your python app, try this: Python app: 在您的python应用中安装cors后,请尝试以下操作:Python应用:

@app.route('/api/', methods=['POST', 'GET'])
def api_post():
    if request.method == 'POST':
        print('post app')
        req = request.json
        print(req)
        return jsonify(name='john')

React app: 反应应用程序:

function App() {
  const [todos, setTodos] = useState(null);
  const [value, setValue] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    const data = { name: value };
    console.log('submit');
    console.log(value);
    fetch('http://127.0.0.1:5000/api/', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then(res => res.json())
      .then(res => console.log(res));
  }

  function handleValue(e) {
    setValue(e.target.value);
  }
  return (
    <section id="app">
      <form action="" onSubmit={handleSubmit}>
        <input type="text" onChange={handleValue} />
        <button> submit </button>
      </form>
    </section>
  );
}
render(<App />, document.querySelector('#root'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM