溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

詳解本地Node.js服務器作為api服務器的解決辦法

發布時間:2020-10-13 04:08:17 來源:腳本之家 閱讀:168 作者:smartphp 欄目:web開發

在看react-native教程的時候,遇到要在手機端調試,需要api服務器,但是由于Node.js自己就作為服務器,沒有apache怎么解決這個問題,用apache和nginx也可以解決,但是有點復雜,我們就使用node已有的模塊解決這個問題.

 //服務器端的代碼
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.' );
});

上面這段代碼在127.0.0.1:3000端口啟動一個本地服務器,但是在手機端是不能訪問的.

我們再啟動另一個node.js服務器來解決這個問題.

//proxy.js
  var http = require('http'), 
     httpProxy = require('http-proxy'); //引入這個模塊

// 新建一個代理 Proxy Server 對象 
var proxy = httpProxy.createProxyServer({}); 

// 捕獲異常 
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.'); 
}); 

// 另外新建一個 HTTP 80 端口的服務器,也就是常規 Node 創建 HTTP 服務器的方法。 
// 在每次請求中,調用 proxy.web(req, res config) 方法進行請求分發 
var server = require('http').createServer(function(req, res) { 
 // 在這里可以自定義你的路由分發 
 var host = req.headers.host, ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; 
 console.log("client ip:" + ip + ", host:" + host); 

 switch(host){ //意思是監聽下面的ip地址,如果匹配就轉到
//127.0.0.1:3000地址
  case '192.168.0.101:8080':  //監聽這個地址
  //這個地址在window上用ipconfig查看,mac/linux用ifconfig查看

  case 'bbs.aaaa.com': 
    proxy.web(req, res, { target: 'http://127.0.0.1:3000' }); //轉到這個地址
  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 以后啟動了proxy服務器.可以通過電腦的ip地址訪問127.0.0.1的api路由了。

如果是使用nginx也可以達到要求,在mac上使用homebrew包管理相當方便

bash下 安裝 brew install nginx

啟動 brew services start nginx

如果安裝了atom編輯器

bash在 直接 atom /usr/local/etc/nginx/nginx.conf 打開配置文件本分以后做出修改

下面是nginx.conf的配置文件

 //nginx.conf

 #原來的文件另存后。直接使用下面內容替換nginx.conf的內容


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; #監聽80880端口
    server_name www.penguu.com 192.168.1.100; #這里是真機要訪問的地址。
    # Mac 通過終端 ifconfig 查看。比如我查看的就是192.168.1.100
    #手機訪問的接口就是 192.168.1.100:8080
    #實際在23行監聽的端口可以是80端口,由于瀏覽器默認就是80端口。但是在mac中有權限問題。所#以就使用8080端口
    # address_book中的service中的地址也要修改路徑是
    # view/service.js->host,修改為 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的 server地址,就是本地node.js服務器的ip地址
      #node.js默認就是127.0.0.1 ,port:3000是在app.js中設定的??梢孕薷?。

    }

  }

  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女