使用express來代理服務(wù)的方法
nodejs和nginx都可以反向代理,解決跨域問題。
本地服務(wù)
const express = require('express')
const app = express()
//如果它在最前面,后面的/開頭的都會被攔截
app.get('/', (req, res) => res.send('Hello World!'))
app.use(express.static('public'));//靜態(tài)資源
app.use('/dist', express.static(path.join(__dirname, 'public')));//靜態(tài)資源
//404
app.use('/test', function (req, res, next) {
res.status(404).send("Sorry can't find that!");
});
app.use(function (req, res, next) {
//TODO 中間件,每個請求都會經(jīng)過
next();
});
app.use(function (err, req, res, next) {
//TODO 失敗中間件,請求錯誤后都會經(jīng)過
console.error(err.stack);
res.status(500).send('Something broke!');
next();
});
app.listen(4000, () => console.log('Example app listening on port 4000!'))
與request配合使用
這樣就將其它服務(wù)器的請求代理過來了
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]));
}
監(jiān)聽本地文件變化
使用nodemon插件。
--watch test指監(jiān)聽根目錄下test文件夾的所有文件,有變化就會重啟服務(wù)。
"scripts": {
"server": "nodemon --watch build --watch test src/server.js"
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
一文詳解Node中module.exports和exports區(qū)別
這篇文章主要介紹了一文詳解Node中module.exports和exports區(qū)別2023-03-03
nodejs基于mssql模塊連接sqlserver數(shù)據(jù)庫的簡單封裝操作示例
這篇文章主要介紹了nodejs基于mssql模塊連接sqlserver數(shù)據(jù)庫的簡單封裝操作,結(jié)合實例形式分析了nodejs中mssql模塊的安裝與操作sqlserver數(shù)據(jù)庫相關(guān)使用技巧,需要的朋友可以參考下2018-01-01
Node.js連接Sql Server 2008及數(shù)據(jù)層封裝詳解
這篇文章主要介紹了Node.js連接Sql Server 2008及數(shù)據(jù)層封裝,結(jié)合實例形式較為詳細(xì)的分析了nodejs連接SQL Server2008數(shù)據(jù)庫以及針對數(shù)據(jù)庫操作方法的封裝與使用相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-08-08
詳解NodeJS框架express的路徑映射(路由)功能及控制
這篇文章主要介紹了詳解NodeJS框架express的路徑映射(路由)功能及控制,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03
淺析node應(yīng)用的timing-attack安全漏洞
本篇文章給大家通過原理的原因分析了node應(yīng)用的timing-attack安全漏洞問題,有興趣的朋友閱讀參考下。2018-02-02

