首先创建web服务,官网上有现成的demo,建议还是自己了解写一遍。新建一个stratServer.js文件,
//require方法导入nodejs的一个对象http
var http = require("http");
//http新建一个web服务,其中function包含两个对象,request是浏览器向服务端发送请求的对象,response是服务端向浏览器写回的对象
http.createServer(function(request,response){
//响应头,200表示成功状态码,输出类型是html类型,编码格式为utf-8
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
//消除在页面刷新一次后dos窗口总会出现两次“访问”
if(request.url!="/favicon.ico"){
//在dos窗口输出
console.log('访问');
//网页上输出
response.write('Hello World!');
//有响应头就需要有响应尾,否则页面一直加载不结束
response.end();
}
//监听8000端口
}).listen(8000);
//web服务创建成功,dos窗口输出
console.log('Server running at http://127.0.0.1:8000/');
函数内部调用
直接在创建web服务的文档后面接着写需求函数,在内部调用。唯一修改的地方就是在原本网页上输出的地方,不在直接输出文本,而是调用定义好的函数。
var http = require('http');
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
if(request.url!="/favicon.ico"){
fun1(response);
response.end();
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
function fun1(res){
console.log("fun1");
res.write("本地调用函数!");
}
函数外部调用
新建一个文件夹,其中放入startServer.js 和 otherfun.js 。先在otherfun.js 中定义外部的函数,如下代码这种写法可支持多种函数的调用,
//支持调用多个函数
module.exports={
fun2:function(res){
console.log("我是fun2");
res.write("fun2");
},
fun3:function(res){
console.log("我是fun3");
res.write("fun3");
}
}
startServer.js文档中,需要调用外部的函数,得先获取它的位置,因为两文件同属一个目录下,所以require导入的地址 ./ 表示当前目录,将其存储在定义的变量中,调用时 变量名.函数名(参数)。
var http = require('http');
var otherfun = require("./otherfun.js");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
if(request.url!="/favicon.ico"){
otherfun.fun2(response);
otherfun.fun3(response);
response.end();
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
字符串调用对应函数
上面代码大致不变,主要修改其中的调用语句。
funname = 'fun2'
otherfun[funname](response); //用字符串调用对应的函数
将函数名传给定义的变量,otherfun.fun2 和 otherfun['fun2'] 效果是一样的,这样的写法更加常用。