使用express来代理服务的方法
作者:纪轻昀 时间:2024-05-03 15:56:50
nodejs和nginx都可以反向代理,解决跨域问题。
本地服务
const express = require('express')
const app = express()
//如果它在最前面,后面的/开头的都会被拦截
app.get('/', (req, res) => res.send('Hello World!'))
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("Sorry can't find that!");
});
app.use(function (req, res, next) {
//TODO 中间件,每个请求都会经过
next();
});
app.use(function (err, req, res, next) {
//TODO 失败中间件,请求错误后都会经过
console.error(err.stack);
res.status(500).send('Something broke!');
next();
});
app.listen(4000, () => console.log('Example app listening on port 4000!'))
与request配合使用
这样就将其它服务器的请求代理过来了
const request = require('request');
app.use('/base/', function (req, res) {
let url = 'http://localhost:3000/base' + req.url;
req.pipe(request(url)).pipe(res);
});
使用http-proxy-middleware
const http_proxy = require('http-proxy-middleware');
const proxy = {
'/tarsier-dcv/': {
target: 'http://192.168.1.190:1661'
},
'/base/': {
target: 'http://localhost:8088',
pathRewrite: {'^/base': '/debug/base'}
}
};
for (let key in proxy) {
app.use(key, http_proxy(proxy[key]));
}
监听本地文件变化
使用nodemon插件。
--watch test
指监听根目录下test文件夹的所有文件,有变化就会重启服务。
"scripts": {
"server": "nodemon --watch build --watch test src/server.js"
}
来源:https://segmentfault.com/a/1190000019540261
标签:express,代理,服务
0
投稿
猜你喜欢
安装Mysql时可能会遇到的一些疑难杂症
2024-01-28 13:30:09
高级MySQL数据库面试问题 附答案
2024-01-13 17:38:10
基于Python实现定时自动给微信好友发送天气预报
2023-09-13 01:24:05
Bootstrap实现渐变顶部固定自适应导航栏
2023-08-23 00:52:40
ASP.NET Core读取配置文件
2024-06-05 09:31:52
python实现自主查询实时天气
2021-07-02 22:43:09
趁热打铁!HTTPGet与HTTPPost的区别详解
2022-07-15 02:46:00
python3中的eval和exec的区别与联系
2023-10-23 05:17:57
vscode搭建go开发环境案例详解
2024-02-07 06:09:48
MySQL数据库的事务和索引详解
2024-01-21 00:40:48
去掉运行JavaScript时IE产生的警告栏
2008-09-11 18:07:00
Python3正则表达式之:(?(id/name)yes-pattern|no-pattern)条件性匹配
2022-04-09 14:46:32
Python爬取qq空间说说的实例代码
2021-04-28 01:29:50
Python3 中文文件读写方法
2021-07-14 20:02:39
vue3封装侧导航文字骨架效果组件
2024-04-27 16:10:03
PHP file_get_contents设置超时处理方法
2023-10-18 05:56:46
mysql建立自定义函数的问题
2024-01-19 06:26:52
vue.js 实现图片本地预览 裁剪 压缩 上传功能
2024-05-11 09:11:06
python multiprocessing模块用法及原理介绍
2021-01-27 06:22:44
Python 3 判断2个字典相同
2021-05-19 23:58:50