入门

  1. var http = require("http");
  2. http.createServer(function (req, res) {
  3. // 发送 HTTP 头部
  4. // HTTP 状态值: 200 : OK
  5. // 内容类型: text/plain
  6. res.writeHead(200, { "Content-type": "text/plain" });
  7. // 发送响应数据 "Hello World"
  8. //响应有两个方法
  9. res.write('hello http\n');//响应的内容
  10. res.end("end");//响应结束
  11. }).listen(8888);
  12. // 终端打印如下信息
  13. console.log('Server running at http://127.0.0.1:8888/');

在cmd命令行输入node http.js
image.png
访问页面
image.png

实战案例

服务端

创建一个服务端的代码

  1. var url = require('url');
  2. var http = require('http');
  3. var server = http.createServer();
  4. function bizLogic (url) {
  5. if (url.path.toLowerCase() === '/login') {
  6. return {
  7. msg: '登录成功!'
  8. }
  9. } else if (url.path.toLowerCase() === '/user') {
  10. return {
  11. msg: [{
  12. name: '小明',
  13. class: '一年级1班'
  14. }, {
  15. name: '小红',
  16. class: '一年级3班'
  17. }]
  18. }
  19. } else {
  20. return {
  21. msg: 404
  22. }
  23. }
  24. }
  25. server.on('request', function (request, response) {
  26. if ('url' in request) {
  27. response.writeHead(200, {
  28. 'Content-Type': 'application/json; charset=utf-8'
  29. });
  30. response.write(JSON.stringify(bizLogic(url.parse(request.url))), 'utf8');
  31. } else {
  32. response.writeHead(404, {
  33. 'Content-Type': 'application/json; charset=utf-8'
  34. });
  35. response.write('找不到页面');
  36. }
  37. response.end();
  38. });
  39. server.listen(88, function () {
  40. console.log('服务器已经开始监听88端口');
  41. });

接着我们要知道URL转换后的样子:

url.parse()方法

方法说明:
使用 url.parse()方法将路径解析为一个方便操作的对象。
第二个参数为 true 表示直接将查询字符串转为一个对象(通过query属性来访问),默认第二个参数为false。

当第二个参数为false时

image.png
如上图,当url为http://localhost:8080/one?a=index&t=article时,
其中,pathname为不包含查询字符串的路径部分(即该路径不包含?后面的那些内容),query即是查询字符串部分

当第二个参数为true时,

image.png
我们可以看到,第二个参数为true时,查询字符串被解析为一个对象了。

客户端

  1. var http = require('http');
  2. var option, req;
  3. option = {
  4. host: '127.0.0.1',
  5. port: 88,
  6. path: '/login'
  7. };
  8. req = http.request(option, function (res) {
  9. if (res.statusCode === 200) {
  10. console.log('ok');
  11. }
  12. res.on('data', function (chunk) {
  13. console.log('the result is ', chunk.toString());
  14. });
  15. });
  16. req.on('error', function (error) {
  17. console.log('something is wrong:', error.message);
  18. });
  19. req.end();

image.png