我开发了几个REST API - GET &这些都是在REACT JS中使用fetch()方法调用的。GET调用工作正常& &;能够在Postman &中获取数据;浏览器控制台。然而,POST调用在邮差上工作,但在浏览器控制台中给出400状态码:
POST http://127.0.0.1:5000/fc/FC001 net::ERR_ABORTED 400 (BAD REQUEST))
注意:当我使用postman 时,上面的API工作得很好。REACT JS代码:
const postFcByRequestNumber = async (RequestNumber, url, name, city) => {
const apiUrl = "http://127.0.0.1:5000/fc/" + RequestNumber;
await fetch(apiUrl, {
method: "POST",
mode: "no-cors",
body: JSON.stringify({
"url": url,
"name": name,
"city": city,
}),
headers: {
"Content-Type": "application/json; charset=UTF-8"
/* Tried below changes, but nothing worked */
// "Content-Type": "application/json"
//"Accept": "application/json",
// "Accept-Encoding": "gzip, deflate, br",
},
})
.then((response) => response.json())
.then((data) => {
console.log("Response for postFcByRequestNumber {FC001} is :", data);
})
.catch((err) => {
console.log(err.message);
});
};
下面是运行在FLASK上的Python代码:
@app.post("/fc/<requestNumber>")
#@app.route("/fc/<requestNumber>", methods=["POST"])
def post_fc_by_requestNumber(requestNumber):
if (not request.view_args['requestNumber']):
return "Please send requestNumber.", 401
if request.is_json:
newRequest = request.get_json()
newRequest["id"] = _find_next_request_id()
newRequest["requestNumber"] = request.view_args['requestNumber']
existingRequests.append(newRequest)
response = jsonify(newRequest)
# Enable Access-Control-Allow -Origin
response.headers.add("Access-Control-Allow-Origin", "*")
return response, 201
return {"error": "Bad Request : Request must be JSON."}, 400
**注:即使我尝试做以下更改,也不会有任何影响&仍然返回400状态码。
- 删除最后一个返回语句(这样可以防止显式返回404)
- 删除路径参数"requestNumber"从Python &
- 删除"cors"从python代码的响应头中获取语句没有影响,它仍然返回404**
另外,我观察到请求头中的内容类型是"text/plain"在浏览器控制台中,而应该是"application/json"通过邮差电话发送。我想这就是问题所在。
所以,我手动添加了"Content-Type"; "application/json;charset = UTF-8"在标题部分,但为什么它仍然使用"text/plain"Request Headers :
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 58
**Content-Type: text/plain;charset=UTF-8**
Host: 127.0.0.1:5000
Origin: http://localhost:3000
Referer: http://localhost:3000/
sec-ch-ua: ".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: cross-site
请建议。
我让它工作了。就像我之前提到的cors &
错误原因:As模式被设置为"no-cors",因此它不会覆盖标题部分中指定的属性,如"content-type"
解决方案:我们需要强制设置mode: "cors"
然后,它只会选择在header中指定的属性,如下所示:
"Content-Type": "application/json; charset=UTF-8"
如果有人知道更多的细节,请分享。