Tanuj Kathuria
Tanuj Kathuria

Reputation: 63

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

I have developed few REST API - GET & POST in Python Flask and these are called from REACT JS using fetch() method. The GET call works fine & able to fetch data in Postman & browser console. However, The POST call works on postman but gives 400 status code in browser console :

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

Note : The above API works perfectly fine when I'm using postman

REACT JS code :

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);
        });
};

Below is the Python code running on FLASK:

@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

**Note : Even if I tried doing following changes, it doesn't have any impact & still returns 400 status code.

  1. Removed the last return statement (so that to prevent returning 404 explicitly)
  2. Removed path parameter "requestNumber" from the url from both Python & React code
  3. Removed "cors" statement from the response headers in python code There is no impact, it still returns 404**

Also, I observed that the content-type in request header is going as "text/plain" in browser console whereas it should be "application/json" as sent via postman call. I think this is the issue.

So, I have manually added "Content-Type": "application/json; charset=UTF-8" in header section but why it is still taking "text/plain" in browser console.

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

Please suggest.

Upvotes: 1

Views: 903

Answers (1)

Tanuj Kathuria
Tanuj Kathuria

Reputation: 63

I got it working. I was very close to it earlier as I mentioned about cors & header properties in fetch() method of React JS earlier.

Reason for error : As mode is set as "no-cors" , so it doesn't override properties specified in header section like "content-type".

Solution: We need to forcefully set mode: "cors" then only it would pick properties specified in headers as below :

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

If anyone knows more details, please share.

Upvotes: 1

Related Questions