首页 > 语言 > JavaScript > 正文

详解本地Node.js服务器作为api服务器的解决办法

2024-05-06 15:10:38
字体:
来源:转载
供稿:网友

在看react-native教程的时候,遇到要在手机端调试,需要api服务器,但是由于Node.js自己就作为服务器,没有apache怎么解决这个问题,用apache和nginx也可以解决,但是有点复杂,我们就使用node已有的模块解决这个问题.

 //服务器端的代码var express = require('express');var app = express();// set up handlebars view enginevar 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);            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选