400坏请求使用axios,烧瓶和反应



我无法通过react js向python-flask服务器发出post请求。我正在使用axios。这个请求对邮递员有效,但我似乎不明白为什么我可以从我的react应用程序发出投递请求。

请参阅烧瓶代码:

@app.route('/match_home_types', methods=['GET', 'POST'])
def match_home_types():
area = request.form['area']
response = jsonify({
'home_types': util.match_area_with_types(area)
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response

我的react redux操作代码:

export const matchHouseTypes = (area) => (dispatch) => {
axios
.post("http://127.0.0.1:5000/match_home_types", area)
.then((res) => {
dispatch({
type: MATCH_TYPES,
payload: res.data.home_types,
});
})
.catch((error) => {
console.log(error.response);
});
};

我的react类组件:

get_house_types = () => {
const { selectedOption } = this.state;
if (selectedOption == "Find a location") {
alert("Please select a valid location");
}
var area = {
area: selectedOption.replace(/(^w|sw)/g, (m) => m.toUpperCase()),
};
console.log("area:", area);
this.props.matchHouseTypes(area);
};

参见以下axios的错误响应:

data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">↵<title>400 Bad Request</title>↵<h1>Bad Request</h1>↵<p>The browser (or proxy) sent a request that this server could not understand.</p>↵"
status: 400
statusText: "Bad Request"

请协助

问题是我没有以正确的方式发送API参数。由于我是通过表格数据发送,我更改了我的代码:

var area = {
area: selectedOption.replace(/(^w|sw)/g, (m) => m.toUpperCase()),
};

至:

const formData = new FormData();
formData.append(
"area",
selectedOption.replace(/(^w|sw)/g, (m) => m.toUpperCase())
);

完整功能:

get_house_types = (e) => {
e.preventDefault();
const { selectedOption } = this.state;
if (selectedOption == "Find a location") {
alert("Please select a valid location");
} else {
const formData = new FormData();
formData.append(
"area",
selectedOption.replace(/(^w|sw)/g, (m) => m.toUpperCase())
);
this.props.matchHouseTypes(formData);
}
};

相关内容

  • 没有找到相关文章

最新更新