一、nodejs服务器介绍
注:‘text/plain’:纯文本,‘application/json’:json格式,‘text/html’:html格式,‘text/plain’:纯文本
var http = require('http');
var onRequest = function(request, response) {
console.log('Request received');
response.writeHead(200, { 'Content-Type': 'text/plain' });
// response.write('Hello from out application');
response.end('Hello from out application');
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('Server started on localhost port 3000');
二、服务器响应json格式文件至客户端
var http = require('http');
var onRequest = function(request, response) {
console.log('Request received');
response.writeHead(200, { 'Content-Type': 'application/json' });
// response.write('Hello from out application');
var myObj = {
name: "hfpp2012",
job: "programmer",
age: 27
};
response.end(JSON.stringify(myObj));
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('Server started on localhost port 3000');
三、服务器响应html格式
var http=require('http');
var fs=require('fs');
var onRequest = function(request, response) {
console.log('Request received');
response.writeHead(200, { 'Content-Type': 'text/html' });
var file= fs.createReadStream(__dirname+'/a.html','utf8');
response.end(file); //或者file.pipe(response)
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('Server started on localhost port 3000');
四、服务器路由
var http=require('http');
var fs=require('fs');
var onRequest = function(request, response) {
var url=request.url;
if(url=='/'||url=='/home'){
response.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname+'/home.html','utf8').pipe(response);
}else if(url=='/review'){
response.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname+'/review.html','utf8').pipe(response);
}else if(url=='/json'){
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({
name:1,
age:2
}))
}
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('Server started on localhost port 3000');