一、node.js的安装
安装教程很多,自己查询,安装完以后,检查一下版本确认安装成功
二、测试
文件放在桌面,向service.js写入如下代码
var http = require('http');
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// 发送响应数据 "nodejs"
response.end('nodejs\n');
}).listen(8080);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8080/');
代码分析:
调用了http的creatServer方法,nodejs用来创建一个http服务器。req 和res 即request 和 response ,请求和响应。
response是响应,我们也可以把它看成是一个对象,有键值对,有方法。
上面我们调用了response的三个方法
res.writeHead(200,{"Content-type":"text/blain"});
这个方法主要管的是向客户端发送一个响应头部 200即是HTTP状态码。状态码后面跟着一个对象,对象里面是一个键值对,Content-type代表文档类型,text/blain代表具体的文档类型。
在cmd执行如下命令:
访问上述网址,运行结果如下
三、服务器端模拟数据返回给前端
内容一:将静态资源文件(html)的请求进行响应;内容二:用post发送并响应数据
var http = require('http');
var fs=require("fs");
var qs = require('querystring');
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/html
var postData="";
var results=[];
switch(request.url){
case "/index.html":
fs.readFile("index.html",function(err,data){
if(err) throw err;
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
response.end();
});
break;
case "/main.html":
fs.readFile("main.html",function(err,data){
if(err) throw err;
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
response.end();
});
break;
case "/Add.js":
request.on("data",function(chunck){
postData+=chunck;
});
request.on("end",function(){
var result = qs.parse(postData);
results.push(result);
response.end(JSON.stringify(results));
});
break;
default:
response.writeHead(200, {'Content-Type': 'text/html'});
response.end("nodejs");
}
}).listen(7798);
不引入qs模块,则返回数据是如上格式。这里需要将数据作为一个对象来解析。
解析处理后结果
[{"myname":"12","age":"13","sex":"nan"}]