NodeJS Web模块

NodeJS Web模块

本文介绍nodeJS的http模块的基本用法,实现简单服务器和客户端

经典Web架构

  • Client:客户端一般指浏览器,通过HTTP协议向服务器发送请求(request)
  • Server:服务器,接受客户端请求,并向服务器发送响应数据(response),主流的有Apache、Nginx、IIS
  • Business:业务逻辑层,核心应用逻辑所在,与数据库、文件系统、外部程序交互
  • Data:数据层,主要由数据库组成

Node服务器

server.js

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 for "+pathname+" received.")
    // 从文件系统中读取请求的内容
    fs.readFile(pathname.substr(1),function (err, data) {
        if (err){
            console.error(err)
            //返回错误信息404
            response.writeHead(404,{"Content-Type":"text/html"})
        }
        else{
            // 请求成功
            response.writeHead(200,{"Content-Type":"text/html"})
            response.write(data.toString())
        }
        response.end()
    })
}).listen(8000) //在8000端口监听

console.log("Server is running at http://127.0.0.1:8000")

在同一目录下新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

运行server.js之后,在浏览器中访问http://127.0.0.1:8000/index.html,就会返回helloworld的页面

Node客户端

client.js

var http = require('http')
// 配置参数
var options = {
    host:'localhost',
    port:'8000',
    path:'/index.html'
}

// 向服务器发送请求
var req = http.request(options, function (response) {
    var body = ''
    // 接受数据块
    response.on('data',function (data) {
        body += data
    })
    response.on('end',function () {
        console.log(body)
    })
})
req.end()

服务器在运行的同时,再开一个终端

$ node client.js

输出为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

GET请求

var http = require('http')
var url = require('url')

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain charset=utf-8'})

    // 解析url参数
    var params = url.parse(req.url,true).query
    res.write('网站名: '+params.name)
    res.write('\n')
    res.write('网站url: '+ params.url)
    res.end()
}).listen(8000)

浏览器中访问http://localhost:8000/?name=百度&url=www.baidu.com

得到响应

POST请求

node没有设置专门对post的请求,一直等待用户输入开销比较大,而是采用了监听用户向服务器发送数据写入的方式实现

var http = require('http')
var fs = require('fs')
var querystring = require('querystring')

var postHTML
fs.readFile('index.html',function (err,data) {
    if (err){
        console.error(err)
    }
    else{
        postHTML = data
    }
})

http.createServer(function (req, res) {
    var data = ""
    req.on('data', function (chunk) {
        data += chunk
    })
    // 数据读完之后解析
    req.on('end',function () {
        // 解析参数
        console.log(data)
        data = querystring.parse(data)
        // 写响应头
        res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'})
        if (data['name'] && data['url']){
            res.write("网站名"+ data['name'])
            res.write("<br>")
            res.write("网站url"+ data['url'])
        }
        else{
            res.write(postHTML)
        }
        res.end()
    })
}).listen(8000)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
</head>
<body>
<form method="post">
    网站名:<input name="name"><br>
    网站url:<input name="url"><br>
    <input type="submit">
</form>
</body>
</html>

访问localhost:8000后输入表单内容并提交,服务器会给出相应

posted @ 2017-11-11 10:19  潇雨危栏  阅读(226)  评论(0编辑  收藏  举报