next.js 错误当请求一个API made in fastapi

xqk2d5yq  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(147)

我在next js中登录,并向fastapi中的api请求返回一个cookie,当我在前端进行获取时,错误发生在我放入凭据时:'include'我只使用html和javascript完成了这个过程,并保存了cookie,但当我在next.js中执行时,我得到了错误

Access to fetch at 'http://127.0.0.1:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

快速API
x一个一个一个一个x一个一个二个x
Next.js

import { LoginModel } from "../models";

export const login = (credencials: LoginModel) => {
    console.log('credencials', credencials);
    const url = 'http://127.0.0.1:8000/login';
    fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(credencials),
    }).then((res) => {
        console.log('res');
        return res.json()
    });
};
yqlxgs2m

yqlxgs2m1#

allow_origins = ['*']按照FastAPI documentation时,我们不能允许凭据。因此,添加CORS中间件的工作代码片段如下所示:

origins = [
    "*",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_methods=["*"],
    allow_headers=["Content-Type"],
)

我在这里删除了allow_credentials=True。你也可以修改它,通过指定允许的来源来允许凭据,如:

origins = [
    "http://localhost:5000/",
    # allowed origins
]

一些额外的建议:
1.不需要指定允许内容类型表头。
1.我建议你从environment variables加载origins。

相关问题