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/plainresponse.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/plainresponse.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/plainresponse.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 !

node.js学习笔记(4) http服务相关推荐

  1. node.js 学习笔记(二)模板引擎和C/S渲染

    node.js 学习笔记(二)模板引擎和C/S渲染 文章目录 node.js 学习笔记(二)模板引擎和C/S渲染 一.初步实现Apache功能 1.1 使用模板引擎 1.2 在 node 中使用模板引 ...

  2. 千锋Node.js学习笔记

    千锋Node.js学习笔记 文章目录 千锋Node.js学习笔记 写在前面 1. 认识Node.js 2. NVM 3. NPM 4. NRM 5. NPX 6. 模块/包与CommonJS 7. 常 ...

  3. 唤醒手腕 - 前端服务器端开发 Node.Js 学习笔记(学习中,更新中)

    唤醒手腕 - Node.Js 学习笔记 唤醒手腕个人的学习记录,时间在2021年12月13日 ~ 2021年12月14日,学习方式看官方文档和B站视频,如有错误或者代码问题的地方,欢迎C站大佬能够帮忙 ...

  4. node.js学习笔记

    # node.js学习笔记标签(空格分隔): node.js---## 一 内置模块学习 ### 1. http 模块 ``` //1 导入http模块 const http =require('ht ...

  5. node.js学习笔记14—微型社交网站

    node.js学习笔记14-微型社交网站 1.功能分析 微博是以用户为中心,因此需要有注册和登录功能. 微博最核心的功能是信息的发表,这个功能包括许多方面,包括:数据库访问,前端显示等. 一个完整的微 ...

  6. Node.js学习笔记8

    Node.js学习笔记8 HTTP服务器与客户端 Node.js的http模块,封装了一个高效的HTTP服务器和一个简易的HTTP客户端 http.server是一个基于事件的HTTP服务器,核心由N ...

  7. node.js学习笔记5——核心模块1

    node.js学习笔记5--核心模块1 Node.js核心模块主要内容包括:(1)全局对象 (2)常用工具 (3)事件机制 (4)文件系统访问 (5)HTTP服务器与客户端 一: 全局对象 Node. ...

  8. node.js学习笔记 - 文件上传(并用七牛云托管)

    文章目录 环境搭建 准备工作 安装相关依赖 代码实现 执行 环境搭建 准备工作 提示:本文采用ts来构建环境,要是以js构建则取掉类型定义即可. 初始化项目 创建目录fileUpload-demo- ...

  9. Node.js (上)(超级详细的node.js学习笔记 !!!)

    目录 一.初识Node.js与内置模块 1.之前知识回顾(为Node.js理解做铺垫) 1.1浏览器中的js的组成部分 1.2 为什么js可以在浏览器中被执行 1.3 为什么浏览器可以操作Bom和Do ...

最新文章

  1. share_ptr_c++11
  2. SDK安装报错HTTP Status 416
  3. 调查:中国内地受访者每年花约40天用于各种“等”
  4. MFC关于Radio按钮分组与选择的操作
  5. 关于写博客的原因以及一点个人说明。
  6. 目标检测常用数据集格式
  7. SAP Spartacus B2B Org Unit树状结构的ghost数据
  8. idea报错:Error:java: JDK isn‘t specified for module ‘xxx‘
  9. javascript_如何不再害怕JavaScript
  10. 王者为什么有些服务器在维护,王者荣耀服务器正在维护中怎么回事 进不去怎么办...
  11. 如何阅读Java源码?已收藏以备后用
  12. 非常优秀的在线绘图网站分享
  13. 智能电视机顶盒开发记录
  14. 洛谷题集——乒乓球(思维、乒乓球比赛规则)
  15. 推荐信息安全书籍27本(含电子书)
  16. docker the input device is not a TTY. If you are using mintty, try prefixing the command with ‘winp
  17. GitHub星数1.3W!五分钟带你搞定Bash脚本使用技巧
  18. MyBatis映射文件如何给数据库的int类型字段“插入”string类型记录
  19. 财务欺诈研究中常用的违规类型
  20. php echo,print,print_r,var_dum的区别

热门文章

  1. 使用python自己搭建一个简单的BP神经网络
  2. Spring与Struts2整合的两种解决方案
  3. Linux技巧:多核下绑定硬件/进程到不同CPU
  4. jaxb int convert to integer
  5. SCA (Service Component Architecture)
  6. hibernate实体的几种状态
  7. .Net之美读书笔记17
  8. 【90】沟通:跨部门管理
  9. android service中显示一个dialog
  10. Python从入门到项目实践(明日科技 吉林大学出版社)