FLASK + VUE:被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态

问题描述 投票:0回答:1

这是我的 myFetch.ts:

const API_ROOT = import.meta.env.VITE_API_ROOT as string;

export function rest(url: string, body?: unknown, method?: string, headers?: HeadersInit){

    return fetch(url, {
        method: method ?? (body ? "POST" : "GET"),
        headers: {
            'Content-Type': 'application/json',
            ...headers
        },
        body: body ? JSON.stringify(body) : undefined
    })
        .then(response => response.ok 
            ? response.json()
            : response.json().then(err => Promise.reject(err))    )
}

export function api(action: string, body?: unknown, method?: string, headers?: HeadersInit){
    return rest(`${API_ROOT}/${action}`, body, method, headers);
}

我的 app.py 函数包含此 CORS 行:

CORS(app)

并且还正确包含我尝试访问的路线的蓝图。当我使用 Postman 时,该路线有效。

我尝试手动设置 CORS 标头,如下所示:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    response.headers.add('Access-Control-Allow-Methods', 'OPTIONS, GET')
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    return response

我还尝试在我的路线中添加装饰器:

@cross_origin(origin="http://localhost:5173", supports_credentials=True)

我尝试将 OPTIONS 方法手动添加到方法中的其余函数中:

    const actualMethod = method === "OPTIONS" ? "OPTIONS" : method ?? (body ? "POST" : "GET");

但是没有任何作用!我仍然收到错误: 从源“http://localhost:5173”获取“http://localhost:8000/api/v1/ports/getports”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。

还有这个: 获取 http://localhost:8000/api/v1/ports/getports net::ERR_FAILED

然后出现“无法获取”错误。

如果有人有任何见解,那就太棒了,谢谢!

python vue.js flask cors web-development-server
1个回答
0
投票

您在哪台服务器上托管该服务?我在 Apache 和 PHP 方面也遇到了类似的问题,问题不在于 API,而在于服务器,该服务器禁用了“选项”请求。

© www.soinside.com 2019 - 2024. All rights reserved.