后端和前端在不同端口上运行,CORS 错误 [英] Backend and Frontend running on different port, CORS error

查看:46
本文介绍了后端和前端在不同端口上运行,CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在不同的端口 (8000,8001) 上运行后端和前端,我无法从 express 服务器创建 res.redirect(...) 并且浏览器显示 CORS 错误(在...处访问 XMLHttpRequest).

I'm running backend and frontend on different port(8000,8001), I can't make res.redirect(...) from express server and the browser shows CORS error(Access to XMLHttpRequest at...).

这是 MEVN(Mongo, Express, Vue, Nodejs) 应用程序,Vue 前端和 express(nodejs) 后端运行在不同的端口上.我在后端实现了 cors() ,它使我的前端可以发出请求(获取、发布)但后端仍然无法使用 res.redirect("...") 重定向前端页面,因为它显示了 CORS错误.

This is MEVN(Mongo, Express, Vue, Nodejs) application, Vue frontend and express(nodejs) backend is running on different port. I implemented cors()on the backend and it makes it possible for my frontend to make requests (get, post)but the backend still can't redirect frontend page, using res.redirect("...") because it shows CORS error.

// Backend
var cors = require('cors');
app.use(cors())
...
function (req, res, next){  // some middleware on backend
  ...
res.redirect('http://urltofrontend');  // cause error


// Error msg on Chrome
Access to XMLHttpRequest at 'http://localhost:8001/' (redirected from 
'http://localhost:8000/api/login') from origin 'null' has been blocked 
by CORS policy: Request header field content-type is not allowed by 
Access-Control-Allow-Headers in preflight response.

我已经完成了 cors() 的实现,它允许我的前端向我的后端发出 http 请求,并且运行良好.但是,来自后端的 res.redirect( ...) 被 CORS 错误阻止.

I've already done implementing cors() and it allows my frontend to make http request to my backend and it works well. However, res.redirect( ...) from backend is blocked by CORS error.

推荐答案

要解决浏览器中的 CORS 错误,您应该将以下 HTTP 标头添加到响应中:

To resolve the CORS error in the browser you should add the following HTTP header to the response:

Access-Control-Allow-Headers: Content-Type

您可以通过添加以下代码来实现:

You can do that by adding the following code:

app.use(cors({
  'allowedHeaders': ['Content-Type'],
  'origin': '*',
  'preflightContinue': true
}));

这篇关于后端和前端在不同端口上运行,CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆