我正在使用React构建一个RESTful Flask应用程序。我正在尝试:
通过React组件渲染我的Jinja2模板
将数据从React组件发布回服务器端Flask
我正在使用Axios进行请求。这是我到目前为止的代码:
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;
模板已渲染,我使用此配置GET
进行数据处理,但是我不知道POST
数据如何从渲染的<forms>
后端进行处理。
我尝试过:
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
路线:
@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'))
一个Nginx反向代理正在用于我的Docker服务(前端和后端),并且我已经添加到 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;
}
但是我只是进入浏览器:
Cannot POST /handle_seeds
如何解决此错误?
答案 0 :(得分:1)
根据您的代码,当您单击“提交”按钮,带有浏览器提交操作的提交表单时,
因此,它正在击中浏览器base_url/handle_seeds
,这就是它引发此错误的原因,
使用此代码,它应该可以工作。
<div id="parent">
<div dangerouslySetInnerHTML={template}/>
<form>
<input type='text' name='name' onChange={this.handleChange}/><br/>
<button type="button" onClick={this.handleSubmit} />
</form>
</div>