我对 React 和 Python 非常陌生,只是想从 React 表单到我的 Python API 中编写一个简单的帖子,以便与 mongoDB 交互。 我有一个 react 表单,它在提交时调用handleSubmit 函数。我希望 handleSubmit 函数 POST 到在端口 5000 上运行的 Python API。我的 React 应用程序在端口 8080 上运行。
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 端点代码:
@app.route('/api/create', methods=['POST'])
def create(self):
if request.method == 'POST':
print(request.args.get('exp_title'))
return True
return False
当我单击按钮时,无法到达我的 python API 端点,因为 React 正在尝试发布到端口 8080 上的路由。我错过了什么?
我尝试使用常规 ajax 调用并得到相同的结果。有一次,我做了一些事情,并在浏览器中收到了 CORS 错误,但我不记得我是如何做到的。
最佳答案
要启用cors,需要安装 pip install -U Flask-cors, 这是网站:https://flask-cors.readthedocs.io/en/latest/ 或者你可以在你的reactjs package.json中的proxy中定义cors,如下所示: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
在 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 应用程序:
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'));
关于python - 将表单数据从 React 句柄提交函数发送到 python API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738364/