Node.js http模块调转页面

1(方法).使用 Node 创建 Web 服务器
// Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP (服务端和客户端),使用 HTTP 服务器或客户端功能必须调用 http 模块,代码如下:
var http=require("http");
var fs=require('fs');
var url=require('url');

http.createServer(function (request,response) {
    var pathname=url.parse(request.url).pathname;
    console.log('request fpr'+pathname+'received');
    fs.readFile(pathname.substr(1),function (err,data) {// substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。
        if(err){
            console.log(err);
            response.writeHead(404,{'Content-Type':"text/html"});
        }else{
            response.writeHead(200,{'Content-Type':"text/html"});
            response.write(data)
        }
        response.end();
    });
}).listen(8080);//可以变量赋值绑定端口
console.log('Server running at http://127.0.0.1:8080/')//为什么不能自动跳转index.html要加。而

 2(方法):
加入图用片不行。的框架
var http=require('http');
var fs=require('fs');
http.createServer(function (req,res) {
    if (req.url === "/"){
        fs.readFile('index.html',function readData(err,data){
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(data)
        })
    }
    else if(req.url === '/index'){
        fs.readFile('index.html',function readData(err,data){
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(data)
        })
    }
    else if(req.url === '/index1'){
        fs.readFile('index1.html',function readData(err,data){
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(data)
        })
    }
    else if(req.url === '/about'){
        fs.readFile('about.html',function readData(err,data){
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(data)
        })
    }
    // else {
    //     res.writeHead(404, { "Content-Type": "text/plain" });
    //     res.end("404 error! File not found.");
    // }
}).listen(8080,'localhost')

 


使用 Node 创建 Web 客户端

var http=require('http');
var options={
    host:'localhost',
    port:'8080',
    path:'/index.html'
};
var callback=function (response) {
    var body='';
    response.on('data',function (data) {
        body+=data;
    });
    response.on('end',function () {
        console.log(body);
    });
}
var req=http.request(options,callback);
req.end();


猜你喜欢

转载自blog.csdn.net/thinkingw770s/article/details/82691879