簡體   English   中英

使用 fetch 方法調用 Python Flask 中開發的 Post API 時,REACT JS 出現 400 錯誤

[英]400 Error in REACT JS while calling Post API developed in Python Flask using fetch method

我在 Python Flask 中開發了一些 REST API - GET & POST,這些是使用 fetch() 方法從 REACT JS 調用的。 GET 調用工作正常,能夠在 Postman 和瀏覽器控制台中獲取數據。 但是, POST 調用適用於郵遞員,但在瀏覽器控制台中提供 400 狀態代碼:

POST http://127.0.0.1:5000/fc/FC001 net::ERR_ABORTED 400 (BAD REQUEST))

注意:當我使用郵遞員時,上面的 API 工作得很好

反應 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 狀態代碼。

  1. 刪除了最后一個 return 語句(以防止顯式返回 404)
  2. 從 Python 和 React 代碼的 url 中刪除了路徑參數“requestNumber”
  3. 從python代碼中的響應頭中刪除了“cors”語句沒有影響,它仍然返回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

請建議。

我讓它工作了。 我之前非常接近它,因為我之前提到過 React JS 的 fetch() 方法中的 cors 和 header 屬性。

錯誤原因:由於模式設置為“no-cors”,因此它不會覆蓋標題部分中指定的屬性,如“content-type”。

解決方案:我們需要強制設置mode: "cors" ,然后它才會選擇標題中指定的屬性,如下所示:

            "Content-Type": "application/json; charset=UTF-8"

如果有人知道更多細節,請分享。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM