nodejs搭建web服务器的方法

本篇文章给大家带来的内容是关于nodejs搭建web服务器的方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

前端获取数据时经常会遇到跨域问题,用 nginx 做反向代理就可以解决此问题。但是 nginx 属于中间件代理,不同开发者布署的 web 服务器地址可能不一样,这样 nginx 的配置就不能做到通用了。

如果能有一个客户端代理,随着项目源代码提交,这样就可以免去不同开发者的代理配置。webpack-dev-server 就是这样的一个客户端代理,但是如果项目没有用到 webpack,那就没办法用了。那能不能仿照写了一个简单的 web 服务器,用于非 webpack 的项目呢。下面是代码,望大佬们批评指正。

const request = require('request');const express = require('express');const path = require('path');const app = express();// 代理配置const proxyTable = {      '/api': {        target: 'http://localhost/api'     }};app.use(function(req, res,next) {      const url = req.url;      if (req.method == 'OPTIONS') {            console.log('options_url: ', url);              //  设置cors 跨域      // res.header("Access-Control-Allow-Origin", req.headers.origin || '*');      // res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");      // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");      // 设置 cookie      // res.header("Access-Control-Allow-Credentials", true);            res.status(200).send('OK');           return;    }     // console.log('req_url: ', url);    next();});// 设置静态目录app.use(express.static(path.join(__dirname, 'static')));app.use('/', function(req, res) {        const url = req.url;       const proxy = Object.keys(proxyTable);        let not_found = true;       for (let index = 0; index = 0) {                   not_found = false;                   const element = proxyTable[k];                    const newUrl = element.target + url.slice(i+k.length);              req.pipe(request({url: newUrl, timeout: 60000},(err)=>{                  if(err){                                console.log('error_url: ', err.code,url);                                 res.status(500).send('');                  }                   })).pipe(res);                    break;          }       }        if(not_found) {              console.log('not_found_url: ', url);          res.status(404).send('Not found');      } else {              console.log('proxy_url: ', url);      }});// 监听端口      const PORT = 8080;app.listen(PORT, () => {      console.log('HTTP Server is running on: http://localhost:%s', PORT);});

登录后复制

PS:static 放静态页面

以上就是nodejs搭建web服务器的方法的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2734858.html

(0)
上一篇 2025年3月8日 01:09:57
下一篇 2025年3月2日 10:23:03

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论