NodeJS HTTP - listen on other port than 80

后端 未结 6 911
情歌与酒
情歌与酒 2021-01-12 00:21

I am running XAMPP on Windows to host an Apache server on port 80. Now I\'m trying to have a NodeJS script running in the background but the problem is that it can only list

6条回答
  •  爱一瞬间的悲伤
    2021-01-12 01:14

    If I want use Apache and Nodejs in same port: npm http-proxy-middleware

    1. Set Apache Port = 81

    [apache dir]/conf/httpd.conf

    ~59: Listen 81

    2. Set nodejs APP port = 3050

    server.listen(3050); // on linux ports<1000 require root privilegue

    3. Use third proxy APP (http-proxy-middleware)

      // https://www.npmjs.com/package/http-proxy-middleware
      var express = require('express');
      var proxy = require('http-proxy-middleware');
    
      // proxy middleware options
      var options = {
          target: 'http://localhost:81', // target host ROOT
          changeOrigin: true, // needed for virtual hosted sites
          ws: true, // proxy websockets
          pathRewrite: {
              // '^/api/old-path' : '/api/new-path',     // rewrite path
              // '^/api/remove/path' : '/path'           // remove base path        
          },
          router: {
              // Examples:
              // when request.headers.host == 'dev.localhost:3000',
              // override target 'http://www.example.org' to 'http://localhost:8000'
              // 'dev.localhost:3000' : 'http://localhost:8000',
              // 'localhost:9000': 'localhost:9002/sub',                 
              // '/sub': 'http://localhost:9002',
    
              'localhost': 'http://localhost:81',         //Root to Apache
              'sub.localhost': 'http://localhost:3050',  // internal
              'sub.mydomain.com': 'http://localhost:3050', //external
          },
      };
    
      // create the proxy (without context)
      // var proxy_wp = proxy(options_wp);
      var proxy_node = proxy(options);
    
      // mount `exampleProxy` in web server
      var app = express();
      app.use(proxy_node);
      app.listen(80);
    

    Then:

    1. localhost:80 - is apache site
    2. sub.localhost:80 - node
    3. localhost:80/sub - node, if you set

    for task runner i use npm PM2

提交回复
热议问题