blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

Viewed 2795

I am trying to create a simple frontend using Typescript and a backend server with Flask and send requests via axios, as I have been using. Somehow I am getting this strange error in the browser console:

Access to XMLHttpRequest at 'http://localhost:5000/api/test' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. POST http://localhost:5000/api/test net::ERR_FAILED

It says my header has some field that is illegal due to CORS setup. But the thing is:

  1. I have a CORS set up in the backend flask server:

in app/__init__.py:

from flask import Flask, render_template, jsonify
from flask_cors import CORS
from random import *
import requests


def create_app(Config):
    app = Flask(__name__)
    CORS(app, support_credentials=True, resources={r"/*": {"origins": "*"}})
    app.config.from_object(Config)
    app.static_folder = app.config["STATIC_FOLDER"]
    app.template_folder = app.config["TEMPLATE_FOLDER"]

    with app.app_context():
        from app.apis.routers import apis
        app.register_blueprint(apis)

    return app



in app/apis/routers.py:


@apis.after_request
def creds(response):
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response


@apis.route('/api/test', methods=["POST"]) 
@cross_origin(supports_credentials=True)
def test():
    data = request.get_json()
    print(data)

    response = {
        "orderTime": "123-456-789",
        "eta": 123
    }
    return jsonify(response)
  1. I was using the header {withCredentials: true} initially. After seeing this error, I removed the header and the request I am sending does NOT have headers AT ALL, but it is still yelling at me that something in the headers is wrong:

in customer.tsx:

import React, {useState} from 'react';
import { useParams } from "react-router-dom";
import axios from 'axios';

import Button from '@mui/material/Button';

interface ParamTypes {
    username: string,
    order_id: string
}

interface headerTypes {
    'Content-Type': string,
    'Access-Control-Allow-Origin': string,
}

// interface Props {
// }

function CustomerContent() {
    // constructor(props: Props) {
    //     super(props);

        
    // }

    let {username, order_id} = useParams<ParamTypes>();
        console.log(username);
        console.log("hi");
    
    const [orderTime, setOrderTime] = useState(0);
    const [ETA, setETA] = useState(0);

    function buttonHandler() {
        let payload = {
            username: username,
            order_id: order_id,
        };

        axios.request<ParamTypes, string>({
            method: 'post',
            url: 'http://localhost:5000/api/test',
            data: payload,
        })
        .then(res => { 
            console.log(res)
        })
              
        setOrderTime(prev => prev + 1);
        setETA(prev => prev + 1);
    }

    return (
        <div>
            <h1>Hello {username}, this page is for your order with ID: {order_id}</h1>
            <p>order placed at: { orderTime } </p>
            <p>ETA: { ETA }</p>

            <Button variant="contained"
                onClick={() => buttonHandler()}>Click to Update Order Status</Button>

        </div>
    )

    
}


export default function customer() {
    return <CustomerContent />;
}

What is wrong with my code?

1 Answers

As it turns out, it only takes a simple setup in the config on the backend side as per How to enable CORS in flask

Thanks @mplungjan for your help!

Related