前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >node http请求 🎴

node http请求 🎴

作者头像
德育处主任
发布2022-08-30 16:46:04
9280
发布2022-08-30 16:46:04
举报
文章被收录于专栏:前端数据可视化

对于前端来说,网络请求主要就是用 ajax 的方式去处理。所以本文也会站在前端角度简单讲解 Node 中如何使用 http 模块。\n\n 前后端对接时,现在常用的请求方法有 GETPOSTPUTPATCHDELETE。当然,还有其他方法,但本文主要面向新手,希望能做到快速起步。所以本文只讲 GETPOST 这两种最最最常用的方法。\n\n 在敲代码前,你首先需要准备一个 编辑器(我用vs code)、浏览器、postman 还有安装好 Node.js 。\n\n 创建服务\n\nNode.js 提供了 http 模块,可用于网络请求。\n\n 创建一个 js 文件,输入以下代码。(本例的文件命名为 index.js)\n\njs\nconst http = require('http')\n\nconst server = http.createServer((res, req) => {\n req.end('hello world')\n})\n\nserver.listen(8000, () => {\n console.log('http://localhost:8000')\n})\n解释:- Node.js 使用 commonjs 语法,所以引入 http 模块使用了 require 的方法。\n- http 模块有一个 createServer 方法,该方法的参数是一个函数,函数里又有2个参数,res 是前端发送请求带过来的信息;req 是后端返回信息给前端时的一些方法和属性的集合。\n- 通过 req.end 方法,可以返回一段字符串给前端。\n- 通过 listen 方法可以设置需要监听的端口号,第二个参数是一个函数,我在控制台里输出 http://localhost:8000 是方便启动服务后方便自己打开这个地址。\n\n 使用 Node.js 运行上面的代码:\n\n\nnode index.js\n\n\n运行完上面的命令,控制台应该会输出 http://localhost:8000 ,此时打开浏览器,输入 http://localhost:8000 后页面上会出现 “hello world”,证明服务创建成功,并且可以访问了。\n\n\n

01.png
01.png

# GET\n\n其实上一步所用的也是 GET 方法来访问后端,但上一步并没有解析参数。get 请求的参数通常是挂在 url 后面的,比如 http://localhost:8000?msg=hello如果有参数,会用 ? 开始,然后使用 参数名=值 的写法。\n\n如果有多个参数,会使用 & 将参数区分开来:\nhttp://localhost:8000?key1=value1&key2=value2&key3=value3\n \在 Node.js 里,如果需要解析 url 的参数,可以使用 node:querystring 模块。 js\nconst http = require('http') // 引入 htpp 模块\nconst querystring = require('node:querystring') // 引入 node:querystring 模块解析url\n\nconst server = http.createServer((req, res) => {\n console.log('method: ', req.method) // 打印请求方法,GET\n\n const url = req.url\n console.log('url: ', url) // 打印被访问的url\n\n req.query = querystring.parse(url.split('?')[1]) // 通过 ? 问号 分隔参数,并使用 querystring.parse 解析问号后面的参数\n console.log('query: ', req.query) // 输出参数\n res.end(JSON.stringify(req.query)) // 将参数返回给前端\n})\n\nserver.listen(8000, () => {\n console.log('http://localhost:8000')\n})\n执行上面的代码,并在浏览器访问 http://localhost:8000/?msg=123&name=leihou\n\n在浏览器会显示出如下内容

02.png
02.png

解析:\n\n- req.url 可以获取到当前访问后端的 url 路径\n- url.split('?')[1] 使用字符串的方法根据 ? 进行切割,然后获取后面那段\n- 使用 querystring.parse 方法将参数转换成对象的形式\n- res.end 将参数返回给前端。\n- 前端在浏览器地址栏输入 http://localhost:8000/?msg=123&name=leihou 时,后端会把参数返回,前端在页面中渲染出返回的参数。# POST\n\nPOST 请求会被 GET 更安全,同时也更麻烦。不能直接在浏览器地址栏输入 url 请求。你可以写一段前端代码,通过 ajax 的方式请求。但本文主要讲解 Node.js ,所以我还是建议你使用 postman 发起 POST 请求。因为 postman 无需你处理跨域等问题。\n\njs\nconst http = require('http')\nconst server = http.createServer((req, res) => {\n if (req.method === 'POST') {\n // 数据格式\n console.log('content-type', req.headers['content-type'])\n // 接收数据\n let postData = ''\n req.on('data', chunk => {\n postData += chunk.toString()\n })\n req.on('end', () => {\n console.log(postData)\n res.end('hello world') // 在这里返回,因为是异步\n })\n }\n})\n\nserver.listen(8000 () => {\n console.log('http://localhost:8000')\n})\nGET 不同,POST 接收数据需要用 req.on('data') 进行接收,用 req.on('end') 处理接收数据完成的操作。\n\n在 Node.js 里除了接收数据外,其他用法和 GET 有点像。\n\n 最后在 postman 访问 http://localhost:8000 ,并在 Bodyraw 里填写 JSON 数据

03.png
03.png

按下 Send 键后,控制台会输出 postman 发送过来的数据。 综合实例如果理解了 GETPOST 请求的话,我们就可以尝试将这两个请求结合起来使用了。js\nconst http = require('http')\nconst querystring = require('node:querystring')\n\nconst server = http.createServer((req, res) => {\n const method = req.method\n const url = req.url\n const path = url.split('?')[0]\n const query = querystring.parse(url.split('?')[1])\n\n // 设置返回格式 JSON\n res.setHeader('Content-type', 'application/json') // 这里返回JSON。如果是 text/html 返回html\n\n // 返回的数据\n const resData = {\n method,\n url,\n path,\n query,\n }\n\n // 返回\n if (method === 'GET') {\n res.end(\n JSON.stringify(resData)\n )\n }\n if (method === 'POST') {\n let postData = ''\n req.on('data', chunk => {\n postData += chunk.toString()\n })\n req.on('end', () => {\n resData.postData = JSON.parse(postData)\n // 返回\n res.end(\n JSON.stringify(resData)\n )\n })\n }\n})\n\nserver.listen(8000, () => {\n console.log('http://localhost:8000')\n})\n上面的代码最主要是判断 methodGET 还是 POST ,因为两者接收数据的方式是不一样的。\n\n 你可以运行上面的代码,尝试在浏览器和 postman 各发送一下 GETPOST 测试一下。\n\n

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档