1、安装nodejs
首先你需要安装nodeJs
那么nodejs官网:http://nodejs.cn/,下载相应版本,一步一步安装。
二、使用nodejs开发服务器后台应用1、创建nodejs应用
直接上代码
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var queryString = require('querystring');
//解析REST请求
function parseReq(response, pathName, queryStr) {//解析请求参数var reqStr = queryString.parse(queryStr);switch (pathName) {//简单实例,解析请求参数获取用户名并通过json数据返回case "/dojoTest/getUser":response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });var str = "{'errNum': 200,'retMsg': '请求成功','data':' 用户名是:" + reqStr.user + "'}";response.write(str);break;//简单实例:通过REST请求方式获取当前时间case "/dojoTest/getTime":response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });response.write("{'errNum': 200,'retMsg': '请求成功','data':' 当前时间:" + new Date().toLocaleString() + "'}");break;//如果没有对应的REST请求,报个501错误给浏览器default:response.writeHead(501, { 'Content-Type': 'application/json;charset=utf-8' });response.write('{"errNum": 501,"retMsg":"请求失败:该请求不存在","data":"null"}');}response.end();
};
//解析静态请求
function staticFileReq(response, pathName, suffixStr) {//读取静态文件并生成流fs.readFile(pathName.substr(1), function(err, data) {if (err) {console.log(err);//HTTP 404 :页面不存在//没找到对应的静态文件怎么办,给个404错误response.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });//响应文件流response.write("页面不存在!404");response.end();} else {//HTTP 200 : 成功if (suffixStr === ".css") {//设置charset=utf-8防止乱码response.writeHead(200, { 'Content-Type': 'text/css;charset=utf-8' });} else {response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });}//响应文件流response.write(data.toString());response.end();}});
}
//创建服务器
http.createServer(function(request, response) {//获取请求地址var requrl = request.url;var urlparse = url.parse(requrl);//请求路径var pathname = urlparse.pathname;//pathname+参数// var urlpath = urlparse.path;//参数var query = urlparse.query;//同上,但参数前多个?// var search = urlparse.search;//后缀var suffix = path.extname(pathname);//控制台显示信息// console.log("Request for " + pathname + " received,path is " + urlpath + ",query is" + query + ",search is" + search);console.log("Request for " + pathname + "received,suffix is " + suffix + ",query is " + query);if (suffix != null && suffix.trim() != "") {//静态文件处理staticFileReq(response, pathname, suffix);} else {//动态请求处理parseReq(response, pathname, query);}//响应结束
}).listen(8081);
//开启后在控制台显示该服务正在运行
console.log('Server running at http://127.0.0.1:8081/');
2、运行编写好的应用
3、从浏览器端发送请求和浏览页面
浏览器发送请求