0

I'm trying to make a POST request from my frontend(react) to my backend(python, flask and MySql) but I'm getting this error message.

Access to XMLHttpRequest at 'http://127.0.0.1:5000/product' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

enter image description here

Network Tab Error Message enter image description here

I am getting this on the server terminal, it's not showing me the POST method. enter image description here

I'm not getting this error message while making a GET request, it's only happening in the POST request but POST is working fine if I make it from POSTMAN.

frontend form code

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { createProduct } from "../../actions/products";
import Button from "./Button";
import Input from "./Input";
import Label from "./Label";

const Modal = ({ showModal, setShowModal }) => {
  const dispatch = useDispatch();
  const [name, setName] = useState("");
  const [unit, setUnit] = useState();
  const [pricePerUnit, setPricePerUnit] = useState();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const product = {
      product_name: name,
      uom_id: parseInt(unit),
      price_per_unit: parseInt(pricePerUnit),
    };
    console.log(product);
    await dispatch(createProduct(product));
  };

  return (
                  <form onSubmit={handleSubmit}>
                    <div>
                      <Label children="Name" />
                      <Input
                        children="Name"
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                      />
                    </div>
                    <div>
                      <Label children="Unit" />
                      <Input
                        children="Unit"
                        type="number"
                        value={unit}
                        onChange={(e) => setUnit(e.target.value)}
                      />
                    </div>
                    <div>
                      <Label children="Price Per Unit" />
                      <Input
                        children="Price Per Unit"
                        type="number"
                        value={pricePerUnit}
                        onChange={(e) => setPricePerUnit(e.target.value)}
                      />
                    </div>
                    <div className="flex items-center justify-end py-6 border-t border-solid border-blueGray-200 rounded-b">
                      <button
                        className="text-red-500 background-transparent font-bold uppercase px-6 py-2 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
                        type="button"
                        onClick={() => setShowModal(false)}
                      >
                        Close
                      </button>
                      <Button type="submit">Save</Button>
                    </div>
                  </form>
  );
};

export default Modal;

createProduct action

import * as api from "../api";
export const createProduct = (product) => async (dispatch) => {
  try {
    const { data } = await api.createProduct(product);
    dispatch({ type: "CREATE", payload: data });
    // toast.success("Product submitted");
  } catch (error) {
    console.log(error);
    // toast.error(error.message);
  }
};

../api API code

import axios from "axios";
const API = axios.create({ baseURL: process.env.REACT_APP_BASE_URL });

export const createProduct = (newProduct) =>
  API.post("/product", newProduct);

backend code:

@app.route('/product', methods=['POST'])
def insert_product():
    request_payload = request.json
    print(request_payload)
    product_id = products_dao.insert_new_product(connection, request_payload)
    response = jsonify({
        'product_id': product_id
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

Postman request screenshot enter image description here

enter image description here

Preflight request screenshot enter image description here

r007
  • 1,566
  • 2
  • 13
  • 22
  • Can you add an example of the postman request? A screenshot of the url, headers, and body. – KMM Dec 12 '21 at 06:45
  • @KeeganM just added, please check – r007 Dec 12 '21 at 06:47
  • Try making a request from postman from localhost and see the response – KMM Dec 12 '21 at 06:49
  • I'm already making a request from postman from localhost – r007 Dec 12 '21 at 06:51
  • localhost and 127.0.0.1 are sometimes viewed as different origins. Like the word "localhost". Most of the time they are interchangeable but in this case possibly not. – KMM Dec 12 '21 at 06:54
  • Also, https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask if CORS happens to not be enabled in your flask file. – KMM Dec 12 '21 at 06:57
  • I added cors by following the steps mentioned in the above post and now it adds new product to the database but it stills show a same error message. – r007 Dec 12 '21 at 07:04
  • Now! I made little bit changes by looking at flask documentation, and now it's not showing an error message. but why it's making two request one of them is preflight. – r007 Dec 12 '21 at 07:23
  • Is it possible the testing environment has a problem? Have you tried a different browser? – KMM Dec 12 '21 at 07:24
  • I added a screenshot please check – r007 Dec 12 '21 at 07:24
  • I tested it on firefox, it still makes two requests one is preflight with OPTIONS method and second one is actual POST request – r007 Dec 12 '21 at 07:26
  • Preflights happen for cross-origin requests automatically to verify the server can handle the origin that is being used to send + the method. After the preflight verifies the server is cross-origin compatible and access-control-allow-origin header, the real request is made – KMM Dec 12 '21 at 07:26
  • so! i think it's fine – r007 Dec 12 '21 at 07:27
  • Yes - if the request was made from the exact same origin, there would be no preflight. Its quite common and okay. automatic. – KMM Dec 12 '21 at 07:27
  • Glad to have helped! Have a good night. – KMM Dec 12 '21 at 07:34
  • Any chance you could accept my answer for those looking for a similar solution? – KMM Dec 13 '21 at 20:02

1 Answers1

0

CORS issues are due to a cross-origin request. Ensure that the server has the CORS settings set up and is returning the Access-Control-Allow-Origin: * header. The preflight will check to see if the cross-site request is allowed, and then the real request will take place.

KMM
  • 646
  • 1
  • 13