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

nodejs在搭建web服务器(简单代理)时

时间:2023-04-03 15:29:54 Node.js

前端在获取数据时经常会遇到跨域问题,使用nginx做反向代理可以解决这个问题。但是nginx是一个中间件代理,不同开发者部署的web服务器地址可能不同,所以nginx的配置不能通用。如果有客户端代理,可以随项目源码一起提交,这样可以省去不同开发者的代理配置。webpack-dev-server就是这样一个客户端代理,但是如果项目没有使用webpack,就没有办法使用了。那么你能为非webpack项目写一个简单的web服务器吗?以下是代码,希望大佬们批评指正。constrequest=require('request');constexpress=require('express');constpath=require('path');constapp=express();//代理配置constproxyTable={'/api':{target:'http://localhost/api'}};app.use(function(req,res,next){consturl=req.url;if(req.method=='OPTIONS'){console.log('options_url:',url);//设置cors跨域//res.header("Access-Control-Allow-Origin",req.headers.origin||'*');//res.header("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With");//res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");//设置cookie//res.header("Access-Control-Allow-Credentials",true);res.status(200).send('OK');return;}//console.log('req_url:',url);next();});//设置静态目录app.use(express.static(path.join(__dirname,'static')));app.use('/',function(req,res){consturl=req.url;constproxy=Object.keys(proxyTable);让not_found=true;for(letindex=0;index=0){not_found=false;constelement=proxyTable[k];constnewUrl=element.target+url.slice(i+k.length);req.pipe(request({url:newUrl,timeout:60000},(err)=>{if(err){console.log('error_url:',err.code,url);res.status(500).发送('');}})).pipe(res);休息;}}if(not_found){console.log('not_found_url:',url);res.status(404).send('未找到');}else{console.log('proxy_url:',url);}});//监听端口constPORT=8080;app.listen(PORT,()=>{console.log('HTTP服务器正在运行:http://localhost:%s',PORT);});PS:static放静态页面