经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Node.js » 查看文章
使用express来代理服务的方法
来源:jb51  时间:2019/6/21 11:18:40  对本文有异议

nodejs和nginx都可以反向代理,解决跨域问题。

本地服务

  1. const express = require('express')
  2. const app = express()
  3.  
  4. //如果它在最前面,后面的/开头的都会被拦截
  5. app.get('/', (req, res) => res.send('Hello World!'))
  6.  
  7. app.use(express.static('public'));//静态资源
  8. app.use('/dist', express.static(path.join(__dirname, 'public')));//静态资源
  9.  
  10. //404
  11. app.use('/test', function (req, res, next) {
  12. res.status(404).send("Sorry can't find that!");
  13. });
  14.  
  15. app.use(function (req, res, next) {
  16. //TODO 中间件,每个请求都会经过
  17. next();
  18. });
  19.  
  20. app.use(function (err, req, res, next) {
  21. //TODO 失败中间件,请求错误后都会经过
  22. console.error(err.stack);
  23. res.status(500).send('Something broke!');
  24. next();
  25. });
  26.  
  27. app.listen(4000, () => console.log('Example app listening on port 4000!'))
  28.  

与request配合使用

这样就将其它服务器的请求代理过来了

  1. const request = require('request');
  2. app.use('/base/', function (req, res) {
  3. let url = 'http://localhost:3000/base' + req.url;
  4. req.pipe(request(url)).pipe(res);
  5. });

使用http-proxy-middleware

  1. const http_proxy = require('http-proxy-middleware');
  2. const proxy = {
  3. '/tarsier-dcv/': {
  4. target: 'http://192.168.1.190:1661'
  5. },
  6. '/base/': {
  7. target: 'http://localhost:8088',
  8. pathRewrite: {'^/base': '/debug/base'}
  9. }
  10. };
  11.  
  12. for (let key in proxy) {
  13. app.use(key, http_proxy(proxy[key]));
  14. }
  15.  

监听本地文件变化

使用nodemon插件。

--watch test指监听根目录下test文件夹的所有文件,有变化就会重启服务。

  1. "scripts": {
  2. "server": "nodemon --watch build --watch test src/server.js"
  3. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号