Mac+nodejs+express搭建一个web服务

1、首先下载nodejs,地址为:https://nodejs.org/en/#download,如下图所示:

具体请看:https://blog.csdn.net/u011619283/article/details/52368759


2、下载好之后直接双击pkg包安装即可,安装好之后可在终端查看node版本和npm版本(注意:最好不要更改安装位置,否则终端无法识别命令),如下图所示:


3、安装好之后再新建一个myweb文件夹,然后使用终端进入到该文件夹下然后使用:npm install express --save安装express,此命令是将express安装到本文件夹,而不是全局文件夹,因此如果以后在其他机器上要使用此项目直接拷贝过去运行即可,不用再重新装express,如下图所示:


4、安装supervisor包,此命令是在启动服务时,如果有更新文件内容,就会重新启动服务,而不用手动退出再重新执行,使用sudo npm install -g supervisor命令来安装,如下图所示:


5、再myweb文件夹创建app.js和HttpServer.js文件,文件内容如下:

(1)HttpServer.js

var express = require('express'); 
var path = require('path');
var http = require("http");
var URL = require('url');
var HttpServer=function(){
	var _this=this;
	this.app=express();
	this.app.use(express.static('webapp'));//设置静态文件路径	
}; 
HttpServer.prototype.init=function(){
		this.app.listen(8888, function () {
		var host = this.address().address
		var port = this.address().port
		console.log("应用实例,访问地址为 http://%s:%s", host, port)
	});
};
HttpServer.prototype.start=function(){
	var _this=this;
	this.app.get('/',function(request,response){_this.getIndex(request,response,_this)});
	this.app.get('/ISAPI',function(request,response){_this.getISAPI(request,response,_this)});
	this.init();
}
HttpServer.prototype.getIndex=function(request,response,_this){
	request.sendFile( __dirname +"/webapp/" + "index.html" );
};
HttpServer.prototype.getISAPI=function(request,response,_this){
	console.log(request.query);
	if(request.method=="GET"){
		console.log("GET");
		http.get(' http://127.0.0.1'+request.url,function(req,res){  
			var html='';  
			req.on('data',function(data){  
				html+=data;  
			});  
			req.on('end',function(){   
				console.log(html);
				response.send(html);
		   });  
		});  
	}else if(request.method=="POST"){
		console.log("GET");
	}else if(request.method=="DELETE"){
		console.log("GET");
	}else if(request.method=="PUT"){
		console.log("GET");
	}


};
module.exports=HttpServer; 

(2)app.js

var HttpServer = require('./HttpServer.js');
var http=new HttpServer();
http.start();

6、在myweb文件夹中新建一个webapp文件夹,并在该文件夹下创建一个index.html文件,文件内容为


7、目前myweb文件夹的内容为:node_modules是安装express包时自动创建的,webapp是手动创建的,注意webapp文件夹与HttpServer.js代码中的this.app.use(express.static('webapp'));//设置静态文件路径和request.sendFile( __dirname +"/webapp/" + "index.html" );中的webapp一致即可。



8、然后启动终端进入到myweb文件夹下,执行:supervisor app.js即可启动http服务,如下图所示:


9、在浏览器中输入:http://127.0.0.1:8888即可输出index.html文件内容,如下图所示:



10、在浏览器中输入:http://127.0.0.1:8888/ISAPI在终端就会打印出信息,说明http服务端收到了浏览器发送的请求,如下图所示:


猜你喜欢

转载自blog.csdn.net/sunxiaoju/article/details/80849538