node.js学习笔记(4) http服务

简介:

Http是互联网时代使用最广泛的协议,没有之一。

Node.js内置了http模块,因此使用node.js搭建一个http服务非常简单。


一、http实例

照旧,先来一个http的"Hello world!",创建http.js文件,代码如下:


//调用http模块
var http = require('http');

var server = http.createServer();
server.on('request', function(request, response) {
    // 发送 HTTP 头部
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 "Hello World !"
    response.end('Hello World !');
}).listen(8000);

console.log('Http server is started.');


运行http.js:


lee@mypc ~/works/nodejs/study4 $ node http.js 
Http server is started.

这时可以看到程序打印完"Http server is started"并没有结束,而是一直占据进程(监听8000端口)。


然后我们另起一个terminal,用curl测试http服务:


lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000"
Hello World !

成功打印出"Hello world !"


二、get请求

创建另一个文件http_get.js。

然后实现逻辑,接收到http请求后先判断request.method,如果不是GET则返回404。如果是GET请求,则用url模块获取参数,并返回接收到的参数。

代码如下:


//调用http模块
var http = require('http');
//调用url模块
var url = require('url');

var server = http.createServer();
server.on('request', function(request, response) {
    if(request.method == 'GET') {
        var params = url.parse(request.url, true).query;
        params = JSON.stringify(params);
        //服务端打印参数
        console.log('Get params:'+params);
        // 发送 HTTP 头部
        // HTTP 状态值: 200 : OK
        // 内容类型: text/plain
        response.writeHead(200, {'Content-Type': 'text/plain'});

        // 把请求参数返回给客户端
        response.end(params+'\n');
    }
    else{
        response.writeHead(404, {'Content-Type': 'text/plain'});
        response.end('Not found !\n');
    }
}).listen(8000);

console.log('Http server is started.');

运行http_get.js:


lee@mypc ~/works/nodejs/study4 $ node http_get.js 
Http server is started.


用curl测试get得到正确结果:


lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000?id=1&name=2"
{"id":"1","name":"2"}
测试post请求则得到"Not found":


lee@mypc ~/works/nodejs/study4 $ curl -d "" "http://localhost:8000"
Not found !




三、post请求
创建一个文件http_post.js。

然后实现逻辑,接收到http请求后先判断request.method,如果不是POST则返回404。如果是POST请求,则获取http body,并返回接收到的内容。

代码如下:



//调用http模块
var http = require('http');

var server = http.createServer();
server.on('request', function(request, response) {
    if(request.method == 'POST') {
        var data_post = '';
        request.on('data', function(data){
            data_post += data;
        });
        request.on('end', function(){
            //服务端打印参数
            console.log('Get body:'+data_post);
            // 发送 HTTP 头部
            // HTTP 状态值: 200 : OK
            // 内容类型: text/plain
            response.writeHead(200, {'Content-Type': 'text/plain'});

            // 把请求参数返回给客户端
            response.end(data_post+'\n');
        })

    }
    else{
        response.writeHead(404, {'Content-Type': 'text/plain'});
        response.end('Not found !\n');
    }
}).listen(8000);

console.log('Http server is started.');

运行http_post.js:


lee@mypc ~/works/nodejs/study4 $ node http_post.js 
Http server is started.


用curl测试post得到正确结果:

lee@mypc ~/works/nodejs/study4 $ curl -d '{"username":"lee","id":1}' "http://localhost:8000"
{"username":"lee","id":1}

测试get请求则得到"Not found":

lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000?id=1&name=2"
Not found !
目录
相关文章
|
1月前
|
Web App开发 监控 Java
|
2月前
|
JavaScript
Node.js【GET/POST请求、http模块、路由、创建客户端、作为中间层、文件系统模块】(二)-全面详解(学习总结---从入门到深化)
Node.js【GET/POST请求、http模块、路由、创建客户端、作为中间层、文件系统模块】(二)-全面详解(学习总结---从入门到深化)
27 0
|
2月前
|
机器学习/深度学习 前端开发 JavaScript
源映射错误:Error: request failed with status 404 源 URL:http://localhost:8080/bootstrap/js/axios-0.18.0.js
源映射错误:Error: request failed with status 404 源 URL:http://localhost:8080/bootstrap/js/axios-0.18.0.js
43 0
源映射错误:Error: request failed with status 404 源 URL:http://localhost:8080/bootstrap/js/axios-0.18.0.js
|
1月前
|
JavaScript
Node.js之http模块
Node.js之http模块
|
2月前
|
前端开发 JavaScript API
JavaScript学习笔记(一)promise与async
JavaScript学习笔记(一)promise与async
|
2月前
|
XML 自然语言处理 前端开发
NLP自学习平台提供了API接口调用服务,这些接口可以通过HTTP GET请求进行调用
【2月更文挑战第7天】NLP自学习平台提供了API接口调用服务,这些接口可以通过HTTP GET请求进行调用
18 2
|
2月前
|
XML JSON 中间件
快速入门Gin框架搭建HTTP服务
快速入门Gin框架搭建HTTP服务
20 0
|
2月前
|
JSON Go 数据格式
一文搞懂Go快速搭建HTTP服务
一文搞懂Go快速搭建HTTP服务
24 0
|
3月前
|
JavaScript 前端开发 网络协议
如何使用Node.js快速创建本地HTTP服务器并实现异地远程访问
如何使用Node.js快速创建本地HTTP服务器并实现异地远程访问
75 0
|
3月前
|
JavaScript
超级实用!详解Node.js中的http模块和fs模块
超级实用!详解Node.js中的http模块和fs模块