这里有新鲜出炉的 Node.JS 入门教程,程序狗速度看过来!
Node.js 是一个基于 Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用 · Node.js 借助事件驱动, 非阻塞 I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用
本篇文章主要介绍了详解本地 Node.js 服务器作为 api 服务器的解决办法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
在看 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中设定的。可以修改。
- }
- }
- }
来源: http://www.phperz.com/article/17/0512/327229.html