nodejs 学习笔记(一) —— 搭建http服务器&url解析

这个系列的博客只用来记录我学习 https://www.bilibili.com/video/av38925557 node.js 教程的总结和遇到的问题。

node.js简介

node.js是一种js运行环境,它利用 Google 的 V8 引擎使得 js 代码能脱离浏览器在服务端运行。

搭建HTTP服务器

新建 http.js 文件:

const http = require('http')

const port = 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('hello world')
})

server.listen(port, () => {
  console.log(`服务器运行在 http://127.0.0.1:${port}/`)
})

在vscode终端 cd 到项目文件夹中并运行 node http.js (这样每次修改都需要重新运行该命令,安装了nodemon就不用)

此时用浏览器访问 http://127.0.0.1:3000 页面显示 ‘hello world’,并在控制台打印出 ‘服务器运行在 http://127.0.0.1:3000/’

Content-Type解释:

将 res.end('hello world') 改为 res.end('<h1>hello world</h1>'),此时页面上显示 '<h1>hello world</h1>',若想让浏览器解析h1标签,则要重新设置响应头

res.setHeader('Content-Type', 'text/html')

就能正常解析html标签了。如果把 res.end('hello world') 改为 res.end('你好世界'),页面显示会出现乱码。解决办法是设置响应头编码格式为utf-8:

res.setHeader('Content-Type', 'text/plain;charset=utf8')

Content-Type 用于定义网络文件的类型和网页的编码,它告诉客户端返回内容的类型和网页编码,客户端以此来决定怎样显示。

常见的媒体格式类型如下:

  • text/html : HTML格式
  • text/plain :纯文本格式
  • text/xml : XML格式
  • image/gif :gif图片格式
  • image/jpeg :jpg图片格式
  • image/png:png图片格式

以application开头的媒体格式类型:

  • application/xhtml+xml :XHTML格式
  • application/xml: XML数据格式
  • application/atom+xml :Atom XML聚合格式
  • application/json: JSON数据格式
  • application/pdf:pdf格式
  • application/msword : Word文档格式
  • application/octet-stream : 二进制流数据(如常见的文件下载)
  • application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

另外一种常见的媒体格式是上传文件之时使用的:

  • multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

  

url解析

稍微改动一下上面的例子:

const http = require('http')

const port = 3000

const server = http.createServer((req, res) => {
    const url = new URL(req.url, 'http://127.0.0.1:3000')
    console.log(url.searchParams.get('name'))
    res.statusCode = 200
    res.setHeader('Content-Type', 'text/plain')
    res.end('hello world')
})

server.listen(port, () => {
    console.log(`服务器运行在 http://127.0.0.1:${port}/`)
})

浏览器访问 http://127.0.0.1:3000/?name=zhangsan 会在后台打印出 zhangsan

url 模块的url.parse()方法在nodejs 11.0以上版本已经弃用,因此采用new URL()进行url解析,再结合searchParams.get()方法获取参数。

注意:new URL(input[, base])

  • input <string> 要解析的绝对或相对的 URL。如果 input 是相对路径,则需要 base。 如果 input 是绝对路径,则忽略 base
  • base <string> | <URL> 如果 input 不是绝对路径,则为要解析的基本 URL。
原文地址:https://www.cnblogs.com/zdd2017/p/14607493.html