詳解本地Node.js服務(wù)器作為api服務(wù)器的解決辦法
在看react-native教程的時(shí)候,遇到要在手機(jī)端調(diào)試,需要api服務(wù)器,但是由于Node.js自己就作為服務(wù)器,沒(méi)有apache怎么解決這個(gè)問(wèn)題,用apache和nginx也可以解決,但是有點(diǎn)復(fù)雜,我們就使用node已有的模塊解決這個(gè)問(wèn)題.
//服務(wù)器端的代碼 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端口啟動(dòng)一個(gè)本地服務(wù)器,但是在手機(jī)端是不能訪問(wèn)的.
我們?cè)賳?dòng)另一個(gè)node.js服務(wù)器來(lái)解決這個(gè)問(wèn)題.
//proxy.js var http = require('http'), httpProxy = require('http-proxy'); //引入這個(gè)模塊 // 新建一個(gè)代理 Proxy Server 對(duì)象 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.'); }); // 另外新建一個(gè) HTTP 80 端口的服務(wù)器,也就是常規(guī) Node 創(chuàng)建 HTTP 服務(wù)器的方法。 // 在每次請(qǐng)求中,調(diào)用 proxy.web(req, res config) 方法進(jìn)行請(qǐng)求分發(fā) var server = require('http').createServer(function(req, res) { // 在這里可以自定義你的路由分發(fā) var host = req.headers.host, ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; console.log("client ip:" + ip + ", host:" + host); switch(host){ //意思是監(jiān)聽(tīng)下面的ip地址,如果匹配就轉(zhuǎn)到 //127.0.0.1:3000地址 case '192.168.0.101:8080': //監(jiān)聽(tīng)這個(gè)地址 //這個(gè)地址在window上用ipconfig查看,mac/linux用ifconfig查看 case 'bbs.aaaa.com': proxy.web(req, res, { target: 'http://127.0.0.1:3000' }); //轉(zhuǎn)到這個(gè)地址 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 以后啟動(dòng)了proxy服務(wù)器.可以通過(guò)電腦的ip地址訪問(wèn)127.0.0.1的api路由了。
如果是使用nginx也可以達(dá)到要求,在mac上使用homebrew包管理相當(dāng)方便
bash下 安裝 brew install nginx
啟動(dòng) brew services start nginx
如果安裝了atom編輯器
bash在 直接 atom /usr/local/etc/nginx/nginx.conf 打開(kāi)配置文件本分以后做出修改
下面是nginx.conf的配置文件
//nginx.conf #原來(lái)的文件另存后。直接使用下面內(nèi)容替換nginx.conf的內(nèi)容 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; #監(jiān)聽(tīng)80880端口 server_name www.penguu.com 192.168.1.100; #這里是真機(jī)要訪問(wèn)的地址。 # Mac 通過(guò)終端 ifconfig 查看。比如我查看的就是192.168.1.100 #手機(jī)訪問(wèn)的接口就是 192.168.1.100:8080 #實(shí)際在23行監(jiān)聽(tīng)的端口可以是80端口,由于瀏覽器默認(rèn)就是80端口。但是在mac中有權(quán)限問(wèn)題。所#以就使用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服務(wù)器的ip地址 #node.js默認(rèn)就是127.0.0.1 ,port:3000是在app.js中設(shè)定的??梢孕薷摹? } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Node.js API詳解之 os模塊用法實(shí)例分析
- Node.js API詳解之 querystring用法實(shí)例分析
- Node.js API詳解之 string_decoder用法實(shí)例分析
- Node.js API詳解之 tty功能與用法實(shí)例分析
- 零基礎(chǔ)之Node.js搭建API服務(wù)器的詳解
- 使用Node.js實(shí)現(xiàn)RESTful API的示例
- 實(shí)現(xiàn)一個(gè)完整的Node.js RESTful API的示例
- 深入分析node.js的異步API和其局限性
- 淺析Node.js 中 Stream API 的使用
- 詳解Nodejs的timers模塊
- Node.js API詳解之 timer模塊用法實(shí)例分析
相關(guān)文章
node.js解決全局安裝pnpm后無(wú)法使用的問(wèn)題
在全局安裝pnpm后,如果出現(xiàn)無(wú)法使用的問(wèn)題,一般是由于沒(méi)有添加系統(tǒng)變量導(dǎo)致的,本文就來(lái)介紹一下node.js解決全局安裝pnpm后無(wú)法使用的問(wèn)題,感興趣的可以了解一下2024-10-10nodejs中實(shí)現(xiàn)sleep功能實(shí)例
這篇文章主要介紹了nodejs中實(shí)現(xiàn)sleep功能實(shí)例,本文講解了sleep功能的開(kāi)發(fā)過(guò)程和使用效果及性能測(cè)試,需要的朋友可以參考下2015-03-03Nodejs使用Mongodb存儲(chǔ)與提供后端CRD服務(wù)詳解
這篇文章主要給大家介紹了關(guān)于Nodejs使用Mongodb存儲(chǔ)與提供后端CRD服務(wù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09nodejs socket服務(wù)端和客戶(hù)端簡(jiǎn)單通信功能
這篇文章主要為大家詳細(xì)介紹了nodejs socket服務(wù)端和客戶(hù)端簡(jiǎn)單通信功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09如何在命令行判斷node.js啟動(dòng)了沒(méi)有(最新)
這篇文章主要介紹了如何在命令行判斷node.js啟動(dòng)了沒(méi)有,使用 tasklist 命令列出所有正在運(yùn)行的進(jìn)程,并使用 findstr 命令過(guò)濾出 Node.js 進(jìn)程,感興趣的朋友跟隨小編一起看看吧2024-06-06