不想用nginx + egg,所以自己研究了一下
express做反向代理到egg。
我的思路:express创建https服务器在443端口,egg创建的http服务器在3001端口,当443接收到请求后转发给3001。
基本实现,欢迎各位大佬评论区指教
首先,express创建https服务器,并转发收到的请求。
需安装依赖:express,express-http-proxy。
const https = require('https') // 引入https模块
const fs = require('fs') // 引入fs模块
const proxy = require('express-http-proxy') // 引入express反向代理模块
const app = require('express')()
const jz_wxapp = `127.0.0.1:3001` // 记账小程序
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use('/jz_wxapp/api/', proxy(jz_wxapp, { // user接受post 和 get 然后proxy代理到 指定端口的服务器
proxyReqPathResolver: (req, res) => { // proxyReqPathResolver 设置转发之后的地址 http:// + jz_wxapp + arr[i]
return require('url').parse(req.url).path
}
})
)
// 导入证书
const options = {
key: fs.readFileSync(".key"),
cert: fs.readFileSync(".pem")
};
// https server 创建
const https_server = https.createServer(options, app);
https_server.listen(443, err => {
console.log('http://127.0.0.1:443');
});
egg的router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
// 与转发过来的对应,注意methods
router.get('/jz_wxapp/api/getUser', controller.home.getUser);
// 与转发过来的对应,注意methods
router.post('//jz_wxapp/api/changeUser', controller.home.changeUser);
};
egg的controller.home
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async getUser() {
const { ctx } = this;
ctx.body = 'hi,这里是egg,我是getUser';
}
async changeUser() {
const { ctx } = this;
ctx.body = 'hi,这里是egg,我是changeUser';
}
}
module.exports = HomeController;
启动443和3001

看一下
](/https://i-blog.csdnimg.cn/blog_migrate/01970cff6849d3e2e0bfd8042aff222d.png#pic_center)
本文介绍如何使用 Express 创建 HTTPS 服务器并作为反向代理,将 443 端口的请求转发到运行在 3001 端口的 Egg 应用。通过这种方式避免使用 nginx,实现简单的服务器配置。文章提到了实现的基本步骤,包括所需依赖、Egg 的路由设置和控制器,以及服务器的启动。
 代理 egg&spm=1001.2101.3001.5002&articleId=108312283&d=1&t=3&u=f2f88e256f954384a811cc7ba5d32133)
1072

被折叠的 条评论
为什么被折叠?



