使用express来代理服务的方法
nodejs和nginx都可以反向代理,解决跨域问题。
本地服务
constexpress=require('express')
constapp=express()
//如果它在最前面,后面的/开头的都会被拦截
app.get('/',(req,res)=>res.send('HelloWorld!'))
app.use(express.static('public'));//静态资源
app.use('/dist',express.static(path.join(__dirname,'public')));//静态资源
//404
app.use('/test',function(req,res,next){
res.status(404).send("Sorrycan'tfindthat!");
});
app.use(function(req,res,next){
//TODO中间件,每个请求都会经过
next();
});
app.use(function(err,req,res,next){
//TODO失败中间件,请求错误后都会经过
console.error(err.stack);
res.status(500).send('Somethingbroke!');
next();
});
app.listen(4000,()=>console.log('Exampleapplisteningonport4000!'))
与request配合使用
这样就将其它服务器的请求代理过来了
constrequest=require('request');
app.use('/base/',function(req,res){
leturl='http://localhost:3000/base'+req.url;
req.pipe(request(url)).pipe(res);
});
使用http-proxy-middleware
consthttp_proxy=require('http-proxy-middleware');
constproxy={
'/tarsier-dcv/':{
target:'http://192.168.1.190:1661'
},
'/base/':{
target:'http://localhost:8088',
pathRewrite:{'^/base':'/debug/base'}
}
};
for(letkeyinproxy){
app.use(key,http_proxy(proxy[key]));
}
监听本地文件变化
使用nodemon插件。
--watchtest指监听根目录下test文件夹的所有文件,有变化就会重启服务。
"scripts":{
"server":"nodemon--watchbuild--watchtestsrc/server.js"
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。