POST请求在我的Nest.js应用程序不工作后部署在Vercel和我收到CORS错误,但CORS在我的应用程序是启用的,当我发送GET请求所有工作。当我在邮差测试我的要求时,一切都在工作。我不确定,但也许这个错误可以通过我使用React查询或vercel问题发生,我没有正确部署我的应用程序。
我收到这样的错误:
访问XMLHttpRequest 'https://server-store.vercel。App/api/auth/login' from origin 'https://next-store-liard-three.vercel。对预飞行请求的响应未通过访问控制检查:请求的资源上不存在"access - control - allow - origin"标头。
我启用了CORS这样的方法:
app.enableCors({
origin: ['http://localhost:3000', 'https://next-store-liard-three.vercel.app'],
allowedHeaders: ['Accept', 'Content-Type'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
});
这是我的文件vercel.json:
{
"version": 2,
"name": "next-store-server",
"buildCommand": "npm start",
"installCommand": "npm install",
"builds": [
{
"src": "dist/main.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/main.js",
"methods": ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
]
}
我也尝试启用CORS的其他方式,但它没有帮助我。
我尝试启用CORS,这样的方法:
const app = await NestFactory.create(AppModule, { cors: true });
客户端I使用Next.js, reactQuery和axios发送请求
import axios from "axios";
import { FAuth, IUser } from "./Auth.types";
const AuthService = {
async registration(dto: IUser) {
const { data } = await axios.post<FAuth>(
`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/registration`,
dto,
);
return data;
},
async login(dto: IUser) {
const { data } = await axios.post<FAuth>(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/login`, dto);
return data;
},
};
这是我自定义的useMutation钩子
export const useRegistration = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.registration(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
export const useLogin = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.login(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
尝试添加"在方法中,这对我有用
vercel.json:
{
"version": 2,
"builds": [{ "src": "src/main.ts", "use": "@vercel/node" }],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}