错误: “从源 'http://....' 访问位于 'https://.....' 的 XMLHttpRequest 已被 CORS 策略阻止: 上不存在 'Access-Control-Allow-Origin' 标头请求资源”。
它在我的本地主机中完美工作,在我托管服务器后,它显示如下错误。
只有当我将图像上传到后端时才会出现问题(我在前端使用React,在后端使用Nodejs)。我已经安装了cors
为什么他们在托管后阻止请求?
我之前遇到过这个错误,请确保您的后端允许您的反应应用程序向资源发出请求。所以就我而言,它是通过添加所需的配置来解决的,如下所示:
app.enableCors({
origin: ['https://localhost:4200', 'https://your-front-end-url.net'],
allowedHeaders: [
'X-Requested-With',
'X-HTTP-Method-Override',
'Content-Type',
'Accept',
'Observe',
'authorization ',
],
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
credentials: true,
});
然后通过添加以下内容将标头设置为响应:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', [
'https://localhost:4200',
'https://your-front-end-url.net',
]);
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
next();
});
并确保在前端请求中添加了适当的标头,例如:
axios.post('Your-back-end-url.com', your_data, {
headers: {
"Content-Type": "application/json",
},
})
希望对你有帮助😉