当前位置: 首页 > 后端技术 > Node.js

Node实现反向代理

时间:2023-04-03 15:44:59 Node.js

跨域问题是前端开发中非常常见的问题。有很多解决方案。jsonp返回Access-Control-Allow-Origin:'*'(需要注意post请求会变成option请求要求后端支持)前端添加代理前端添加代理以vue-cli为例,前端-end添加代理dev:{env:require('./dev.env'),port:8888,autoOpenBrowser:true,assetsSubDirectory:'static',assetsPublicPath:'/',proxyTable:{'/api':{target:'http://localhost:3000',changeOrigin:true,}}其中'/api'为接口前缀,target为后端服务地址frontend请求示例vm.$http.post('/api/reg',JSON.stringify(info)).then(()=>{},()=>{});反向代理反向代理可以理解为指定一个服务地址作为内部服务器地址。为什么需要反向代理如果只是作为接口请求,其实在前端搭建一个代理服务器就可以了,但是代理服务器不能满足所有的日常开发。比如单点登录的实现,需要服务器做302重定向。但是当前端文件没有部署到后端服务器时,set-cookie是无法成功植入cookie登录信息的。这就需要在后端服务器上加一个反向代理。例子如下consthttp=require('http');consthttpProxy=require('http-proxy');constproxy=httpProxy.createProxyServer();constproxyServer=http.createServer((req,res)=>{proxy.web(req,res,{target:'http://localhost:8888',});});proxyServer.listen(8088,()=>{console.log('proxyserverisrunning');});这样就可以在8088端口进行前端开发了,当然热加载功能是在前端的8888端口服务器