前端在获取数据时经常会遇到跨域问题,使用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
