本文简介

点赞 + 关注 + 珍藏 = 学会了


对于前端来说,网络申请次要就是用 ajax 的形式去解决。所以本文也会站在前端角度简略解说 Node 中如何应用 http 模块。


前后端对接时,当初罕用的申请办法有 GETPOSTPUTPATCHDELETE。当然,还有其余办法,但本文次要面向老手,心愿能做到疾速起步。所以本文只讲 GETPOST 这两种最最最罕用的办法。


在敲代码前,你首先须要筹备一个 编辑器(我用vs code)、浏览器、postman 还有装置好 Node.js



创立服务

Node.js 提供了 http 模块,可用于网络申请。


创立一个 js 文件,输出以下代码。(本例的文件命名为 index.js)

const http = require('http')const server = http.createServer((res, req) => {  req.end('hello world')})server.listen(8000, () => {  console.log('http://localhost:8000')})

解释:

  • Node.js 应用 commonjs 语法,所以引入 http 模块应用了 require 的办法。
  • http 模块有一个 createServer 办法,该办法的参数是一个函数,函数里又有2个参数,res 是前端发送申请带过去的信息;req 是后端返回信息给前端时的一些办法和属性的汇合。
  • 通过 req.end 办法,能够返回一段字符串给前端。
  • 通过 listen 办法能够设置须要监听的端口号,第二个参数是一个函数,我在控制台里输入 http://localhost:8000 是不便启动服务后不便本人关上这个地址。


应用 Node.js 运行下面的代码:

node index.js

运行完下面的命令,控制台应该会输入 http://localhost:8000 ,此时关上浏览器,输出 http://localhost:8000 后页面上会呈现 “hello world”,证实服务创立胜利,并且能够拜访了。



GET

其实上一步所用的也是 GET 办法来拜访后端,但上一步并没有解析参数。

get 申请的参数通常是挂在 url 前面的,比方 http://localhost:8000?msg=hello

如果有参数,会用 ? 开始,而后应用 参数名=值 的写法。

如果有多个参数,会应用 & 将参数辨别开来:

http://localhost:8000?key1=value1&key2=value2&key3=value3


Node.js 里,如果须要解析 url 的参数,能够应用 node:querystring 模块。

const http = require('http') // 引入 htpp 模块const querystring = require('node:querystring') // 引入 node:querystring 模块解析urlconst server = http.createServer((req, res) => {  console.log('method: ', req.method) // 打印申请办法,GET  const url = req.url  console.log('url: ', url) // 打印被拜访的url  req.query = querystring.parse(url.split('?')[1]) // 通过 ? 问号 分隔参数,并应用 querystring.parse 解析问号前面的参数  console.log('query: ', req.query) // 输入参数  res.end(JSON.stringify(req.query)) // 将参数返回给前端})server.listen(8000, () => {  console.log('http://localhost:8000')})

执行下面的代码,并在浏览器拜访 http://localhost:8000/?msg=123&name=leihou

在浏览器会显示出如下内容


解析:

  • req.url 能够获取到以后拜访后端的 url 门路
  • url.split('?')[1] 应用字符串的办法依据 ? 进行切割,而后获取前面那段
  • 应用 querystring.parse 办法将参数转换成对象的模式
  • res.end 将参数返回给前端。
  • 前端在浏览器地址栏输出 http://localhost:8000/?msg=123&name=leihou 时,后端会把参数返回,前端在页面中渲染出返回的参数。



POST

POST 申请会被 GET 更平安,同时也更麻烦。不能间接在浏览器地址栏输出 url 申请。

你能够写一段前端代码,通过 ajax 的形式申请。但本文次要解说 Node.js ,所以我还是倡议你应用 postman 发动 POST 申请。因为 postman 无需你解决跨域等问题。


const http = require('http')const server = http.createServer((req, res) => {  if (req.method === 'POST') {    // 数据格式    console.log('content-type', req.headers['content-type'])    // 接收数据    let postData = ''    req.on('data', chunk => {      postData += chunk.toString()    })    req.on('end', () => {      console.log(postData)      res.end('hello world') // 在这里返回,因为是异步    })  }})server.listen(8000 () => {  console.log('http://localhost:8000')})

GET 不同,POST 接收数据须要用 req.on('data') 进行接管,用 req.on('end') 解决接收数据实现的操作。

Node.js 里除了接收数据外,其余用法和 GET 有点像。


最初在 postman 拜访 http://localhost:8000 ,并在 Bodyraw 里填写 JSON 数据

按下 Send 键后,控制台会输入 postman 发送过去的数据。



综合实例

如果了解了 GETPOST 申请的话,咱们就能够尝试将这两个申请联合起来应用了。

const http = require('http')const querystring = require('node:querystring')const server = http.createServer((req, res) => {  const method = req.method  const url = req.url  const path = url.split('?')[0]  const query = querystring.parse(url.split('?')[1])  // 设置返回格局 JSON  res.setHeader('Content-type', 'application/json') // 这里返回JSON。如果是 text/html 返回html  // 返回的数据  const resData = {    method,    url,    path,    query,  }  // 返回  if (method === 'GET') {    res.end(      JSON.stringify(resData)    )  }  if (method === 'POST') {    let postData = ''    req.on('data', chunk => {      postData += chunk.toString()    })    req.on('end', () => {      resData.postData = JSON.parse(postData)      // 返回      res.end(        JSON.stringify(resData)      )    })  }})server.listen(8000, () => {  console.log('http://localhost:8000')})

下面的代码最次要是判断 methodGET 还是 POST ,因为两者接收数据的形式是不一样的。


你能够运行下面的代码,尝试在浏览器和 postman 各发送一下 GETPOST 测试一下。



举荐浏览

《『uni-app』web-view》

《『uni-app、小程序』蓝牙连贯、读写数据全过程》

《Vue3 - $attrs 的几种用法(1个或多个根元素、Options API 和 Composition API)》

《Vue3 过10种组件通信形式》
点赞 + 关注 + 珍藏 = 学会了