1. 程式人生 > 實用技巧 >使用express來代理服務的方法

使用express來代理服務的方法

本地服務

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"
}