【问题标题】:blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response [duplicate]被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型 [重复]
【发布时间】:2021-12-24 22:24:38
【问题描述】:

我正在尝试使用 Typescript 创建一个简单的前端,并使用 Flask 创建一个后端服务器,并通过 axios 发送请求,就像我一直在使用的那样。不知何故,我在浏览器控制台中收到了这个奇怪的错误:

从源“http://localhost:3000”访问“http://localhost:5000/api/test”处的 XMLHttpRequest 已被 CORS 策略阻止:访问不允许请求标头字段内容类型-预检响应中的 Control-Allow-Headers。 POST http://localhost:5000/api/test net::ERR_FAILED

它说我的标题有一些由于 CORS 设置而非法的字段。但问题是:

  1. 我在后端烧瓶服务器中设置了 CORS:

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



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. 我最初使用的是标题{withCredentials: true}。看到此错误后,我删除了标头,并且我发送的请求根本没有标头,但它仍然对我大吼大叫,标头中的某些内容是错误的:

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

我的代码有什么问题?

【问题讨论】:

标签: javascript reactjs typescript flask cors


【解决方案1】:

事实证明,它只需要根据How to enable CORS in flask在后端的配置中进行简单设置

感谢@mplungjan 的帮助!

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 2019-09-16
    • 2020-02-27
    • 2021-08-06
    • 1970-01-01
    • 2021-08-24
    • 2016-05-15
    • 2020-02-24
    相关资源
    最近更新 更多