Node 代理 Demo 示例
index.js
var express = require('express');
const path = require('path');
const http = require('http');
// 引入json解析中间件 解决上传内容太多失败
let bodyParser = require('body-parser');
var { createProxyMiddleware } = require('http-proxy-middleware');
var app = express();
// console.log(proxy);
app.use('/qwee', createProxyMiddleware({
target: 'http://127.0.0.1', //转发到的地址
changeOrigin: true, // needed for virtual hosted sites
// ws: true, // 代理websocket
pathRewrite: {
'^/qwee': '', // rewrite path
},
// router: {
// // 当请求localhost:3000/api时,会转发到http://localhost:8080,
// 'http://localhost:8888/qwee/qqqq': 'http://127.0.0.1'
// }
}))
app.use('/wer', createProxyMiddleware({
target: 'http://127.0.0.1', //转发到的地址
changeOrigin: true, // needed for virtual hosted sites
// ws: true, // 代理websocket
pathRewrite: {
'^/wer': '', // rewrite path
},
// router: {
// // 当请求localhost:3000/api时,会转发到http://localhost:8080,
// 'http://localhost:8888/qwee/qqqq': 'http://127.0.0.1'
// }
}))
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, './')))
app.use('/data', require('./routes.js'));
// 创建服务
let port = 8888;
let server = app.listen(port);
server.on('error', (error) => {
reject(error)
});
server.on('listening', async () => {
console.log(`Service ${port} port started successfully`);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
routes.js
const express = require("express");
const router = express.Router();
// 获取所有数据
router.get('/get', (req, res, next) => {
let { pageSize, pageNo, page_id, _id, bid } = req.query;
res.json({ data: 200 });
})
module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
axios.get('http://localhost:8888/qwee/swd/deploy/get?pageNo=1&pageSize=10')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get('http://localhost:8888/wer/swd/deploy/get?pageNo=1&pageSize=10')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
上次更新: 2024/01/30, 00:35:17
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20