簡體   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

我正在嘗試使用 Typescript 創建一個簡單的前端,並使用 Flask 創建一個后端服務器,並通過axios發送請求,正如我一直在使用的那樣。 不知何故,我在瀏覽器控制台中收到了這個奇怪的錯誤:

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

它說我的標題有一些由於 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 />;
}

我的代碼有什么問題???

事實證明,根據如何在flask中啟用CORS,只需要在后端的配置中進行簡單的設置

感謝@mplungjan 的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM