node学习基础篇三

一、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');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值