我最近构建了一个新项目,它在前端做出反应,并使用 Node js 服务器作为后端。 API 调用在带有 cors 的 localhost 上工作,但是当我发布到 vercel 时,无论我如何更改 cors 设置,我都会遇到相同的错误。如果有人知道如何修复此错误:
Access to XMLHttpRequest at 'https://portfolio-5-0-backend.vercel.app/api/send-email' from origin 'https://portfolio-5-0-frontend.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
坐标设置:
const allowedOrigins = ["https://portfolio-5-0-frontend-2c3fpno4h-kroplewskims-projects.vercel.app", "https://portfolio-5-0-frontend.vercel.app"];
const corsOptions = {
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, { origin: true });
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Access-Control-Allow-Origin", "Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"],
credentials: false,
};
app.options("*", cors(corsOptions));
app.use(cors(corsOptions));
app.use(bodyParser.json());
反应API调用:
const onSubmit = handleSubmit(async (data) => {
try {
PushNotification("Sending email...", "bg-info");
const response = await axios.post("https://portfolio-5-0-backend.vercel.app/api/send-email", {
Email: data.Email,
Name: data.Name,
Message: data.Message,
}, {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
if (response.status === 200) {
PushNotification("Email sent successfully!...", "bg-success");
}
} catch (e) {
PushNotification("Failed to send email", "bg-error");
console.log(e);
}
});
我尝试进行 API 调用的网址是:https://portfolio-5-0-frontend.vercel.app/
试试这个:
app.use(cors( {
credentials: true,
preflightContinue: true,
methods: ['GET', 'POST', 'PUT', 'PATCH' , 'DELETE', 'OPTIONS'],
origin: ['*','http://localhost','your_domain'] } ));