简体   繁体   English

被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型

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

I'm trying to create a simple frontend using Typescript and a backend server with Flask and send requests via axios , as I have been using.我正在尝试使用 Typescript 创建一个简单的前端,并使用 Flask 创建一个后端服务器,并通过axios发送请求,正如我一直在使用的那样。 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.它说我的标题有一些由于 CORS 设置而非法的字段。 But the thing is:但问题是:

  1. I have a CORS set up in the backend flask server:我在后端烧瓶服务器中设置了一个 CORS:

in app/__init__.py :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 :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.我最初使用标题{withCredentials: true} 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 :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 ???我的代码有什么问题???

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事实证明,根据如何在flask中启用CORS,只需要在后端的配置中进行简单的设置

Thanks @mplungjan for your help!感谢@mplungjan 的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 XMLHttpRequest 已被 CORS 策略阻止:请求 header 字段内容类型在预检响应中不允许访问控制允许标头 - XMLHttpRequest has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response 根据 CORS 预检响应中的 header 'Access-Control-Allow-Headers' 不允许使用 'content-type' - ‘content-type’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response 被 CORS 阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求 header 字段授权 - Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response Slack 传入 webhook:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-type - Slack incoming webhook: Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response React.js + PHP/Apache:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型 - React.js + PHP/Apache: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response CI和Angular4:在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段的内容类型 - CI and Angular4 : Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response CORS:飞行前响应中Access-Control-Allow-Headers不允许Content-Type - CORS: Content-Type is not allowed by Access-Control-Allow-Headers in preflight response 请求标头字段Access-Control-Allow-Headers在预检响应中不允许使用Access-Control-Allow-Headers - Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response 获取 API CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段授权 - Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权 - CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM