[英]400 bad Request using axios, flask and react
我無法通過 react js 向 python-flask 服務器發出發布請求。 我正在使用 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);
});
};
我的反應類組件:
get_house_types = () => {
const { selectedOption } = this.state;
if (selectedOption == "Find a location") {
alert("Please select a valid location");
}
var area = {
area: selectedOption.replace(/(^\w|\s\w)/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|\s\w)/g, (m) => m.toUpperCase()),
};
到:
const formData = new FormData();
formData.append(
"area",
selectedOption.replace(/(^\w|\s\w)/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|\s\w)/g, (m) => m.toUpperCase())
);
this.props.matchHouseTypes(formData);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.