Explain the solution of local Node. js server as api server in detail

  • 2021-07-24 09:47:17
  • OfStack

When reading react-native tutorial, we need api server to debug on the mobile phone. However, since Node. js is itself a server, how to solve this problem without apache can be solved with apache and nginx, but it is a bit complicated, so we use the existing modules of node to solve this problem.


 // Server-side code 
var express = require('express');

var app = express();

// set up handlebars view engine
var handlebars = require('express3-handlebars')
  .create({ defaultLayout:'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', process.env.PORT || 3000);

app.use(express.static(__dirname + '/public'));

var fortuneCookies = [
  "Conquer your fears or they will conquer you.",
  "Rivers need springs.",
  "Do not fear what you don't know.",
  "You will have a pleasant surprise.",
  "Whenever possible, keep it simple.",
];

app.get('/', function(req, res) {
  res.render('home');
});
app.get('/about', function(req,res){
  var randomFortune = 
    fortuneCookies[Math.floor(Math.random() * fortuneCookies.length)];
  res.render('about', { fortune: randomFortune });
});

// 404 catch-all handler (middleware)
app.use(function(req, res, next){
  res.status(404);
  res.render('404');
});

// 500 error handler (middleware)
app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500);
  res.render('500');
});

app.listen(app.get('port'), function(){
 console.log( 'Express started on http://localhost:' + 
  app.get('port') + '; press Ctrl-C to terminate.' );
});

The above code starts a local server on port 127.0. 0.1: 3000, but it cannot be accessed on the mobile phone.

Let's start another node. js server to solve this problem.


//proxy.js
  var http = require('http'), 
     httpProxy = require('http-proxy'); // Introducing this module 

//  New 1 Agents  Proxy Server  Object  
var proxy = httpProxy.createProxyServer({}); 

//  Catch exceptions  
proxy.on('error', function (err, req, res) { 
 res.writeHead(500, { 
  'Content-Type': 'text/plain' 
 }); 
 res.end('Something went wrong. And we are reporting a custom error message.'); 
}); 

//  Additionally create a new 1 A  HTTP 80  Port, which is the server of the general  Node  Create  HTTP  The method of the server.  
//  On each request, call the  proxy.web(req, res config)  Method for request distribution  
var server = require('http').createServer(function(req, res) { 
 //  Here you can customize your routing distribution  
 var host = req.headers.host, ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; 
 console.log("client ip:" + ip + ", host:" + host); 

 switch(host){ // It means listening to the following ip Address , If there is a match, go to 
//127.0.0.1:3000 Address 
  case '192.168.0.101:8080':  // Monitor this address 
  // This address is in window Used ipconfig View ,mac/linux Use ifconfig View 

  case 'bbs.aaaa.com': 
    proxy.web(req, res, { target: 'http://127.0.0.1:3000' }); // Go to this address 
  break; 

  default: 
    res.writeHead(200, { 
      'Content-Type': 'text/plain' 
    }); 
    res.end('Welcome to my server!'); 
 } 
}); 

console.log("listening on port 8080") 
server.listen(8080);

node proxy. js started the proxy server. The api route of 127.0. 0.1 can be accessed through the ip address of the computer.

If you use nginx, you can also meet the requirements. It is quite convenient to use homebrew packet management on mac

Install brew install nginx under bash

Start brew services start nginx

If you have an atom editor installed

bash modifications were made after atom/usr/local/etc/nginx/nginx. conf opened the profile part directly

The following is the configuration file for nginx. conf


 //nginx.conf

 # After the original file is saved. Replace directly with the following nginx.conf Content of 


events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;

  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';



  sendfile    on;
  #tcp_nopush   on;

  #keepalive_timeout 0;
  keepalive_timeout 65;



  server {
    listen 8080; # Eavesdropping 80880 Port 
    server_name www.penguu.com 192.168.1.100; # Here is the address to be visited by the real machine. 
    # Mac  Through the terminal  ifconfig  Check. For example, what I'm looking at is 192.168.1.100
    # The interface of mobile phone access is  192.168.1.100:8080
    # Actual in 23 The port for row listening can be 80 Port, because the browser defaults to 80 Port. But in mac There is a permission problem in. Institute # For the purpose of using 8080 Port 
    # address_book In service The address in also needs to be modified. The path is 
    # view/service.js->host, Modify to  192.168.1.100 : 8080

    #access_log /var/log/nginx/test.log;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-Nginx-Proxy true;
      proxy_set_header Connection "";
      proxy_pass   http://127.0.0.1:3000; # address_book Adj.  server The address is local node.js Server's ip Address 
      #node.js The default is 127.0.0.1  , port:3000 Is in app.js Is set in the. It can be modified. 

    }

  }

  }


Related articles: