nodeJS搭一个简单的(代理)web服务器
程序员文章站
2023-08-26 17:57:48
前端获取数据时经常遇见跨域问题,以前一直用nginx做反向代理。最近在用vuejs,发现webpack-dev-server的代理简单好用。于是仿照写了一个简单的web服务器,用于非webpack的项目。 ......
前端获取数据时经常遇见跨域问题,以前一直用nginx做反向代理。最近在用vuejs,发现webpack-dev-server的代理简单好用。于是仿照写了一个简单的web服务器,用于非webpack的项目。
1 const request = require('request'); 2 const express = require('express'); 3 const path = require('path'); 4 5 const app = express(); 6 7 const proxytable = { 8 '/wcf': { 9 target: 'http://localhost/wcf' 10 } 11 }; 12 13 app.use(function(req, res,next) { 14 const url = req.url; 15 if (req.method == 'options') { 16 console.log('options_url: ', url); 17 18 // res.header("access-control-allow-origin", req.headers.origin || '*'); 19 // res.header("access-control-allow-headers", "content-type, authorization, x-requested-with"); 20 // res.header("access-control-allow-methods", "put,post,get,delete,options"); 21 22 // res.header("access-control-allow-credentials", true); 23 24 res.status(200).send('ok'); 25 return; 26 } 27 28 // console.log('req_url: ', url); 29 next(); 30 }); 31 32 33 app.use(express.static(path.join(__dirname, 'static'))); 34 35 app.use('/', function(req, res) { 36 const url = req.url; 37 const proxy = object.keys(proxytable); 38 let not_found = true; 39 for (let index = 0; index < proxy.length; index++) { 40 const k = proxy[index]; 41 const i = url.indexof(k); 42 if (i >= 0) { 43 not_found = false; 44 const element = proxytable[k]; 45 const newurl = element.target + url.slice(i+k.length); 46 req.pipe(request({url: newurl, timeout: 60000},(err)=>{ 47 if(err){ 48 console.log('error_url: ', err.code,url); 49 res.status(500).send(''); 50 } 51 })).pipe(res); 52 break; 53 } 54 } 55 if(not_found) { 56 console.log('not_found_url: ', url); 57 res.status(404).send('not found'); 58 } else { 59 console.log('proxy_url: ', url); 60 } 61 }); 62 63 const port = 8080; 64 app.listen(port, () => { 65 console.log('http server is running on: http://localhost:%s', port); 66 });
上一篇: 失恋心理治疗帮你走出失恋阴影
下一篇: 做梦梦见前男友?是恋恋不舍的吗?