Ole*_*ndr 3 deployment node.js cors vercel nestjs
在 Vercel 上部署后,我的 Nest.js 应用程序中的 POST 请求不起作用,并且收到 CORS 错误,但我的应用程序中的 cors 已启用,并且当我发送 GET 请求时,一切正常。当我在邮递员中测试我的请求时,一切正常。我不确定,但也许这个错误可能是由于我使用 React Query 或 vercel 问题而发生的,并且我没有正确部署我的应用程序。
我收到这样的错误:
从源“https://next-store-liard- Three.vercel.app”访问“https://server-store.vercel.app/api/auth/login”处的 XMLHttpRequest 已被 CORS 策略阻止:响应预检请求未通过访问控制检查:请求的资源上不存在“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,
});
Run Code Online (Sandbox Code Playgroud)
这是我的文件 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"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我也尝试以其他方式启用 CORS,但这对我没有帮助。
我尝试启用CORS,这样的方法:
const app = await NestFactory.create(AppModule, { cors: true });
Run Code Online (Sandbox Code Playgroud)
在客户端我使用 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;
},
};
Run Code Online (Sandbox Code Playgroud)
这是我的自定义 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",
});
},
});
Run Code Online (Sandbox Code Playgroud)
小智 6
尝试将“选项”添加到方法中,这对我有用
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"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1253 次 |
| 最近记录: |