Node.js GET/POST请求
在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。
表单提交到服务器一般都使用 GET/POST 请求。
本章节我们将为大家介绍 Node.js GET/POST请求。
获取GET请求内容
由于 GET 请求直接被嵌入在路径中,URL 是完整的请求路径,包括了 ? 后面的部分,因此你可以手动解析后面的内容作为 GET 请求的参数。
node.js 中 可以使用 URL 构造函数解析请求的 URL。
URL 对象是 Node.js 中用于解析和操作 URL 的一种标准工具。它提供了方便的接口来访问和修改 URL 的各个组成部分,如协议、主机名、路径、查询参数等。
实例
const http = require('http'); const util = require('util'); http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); // 使用 URL 构造函数解析请求的 URL const myUrl = new URL(req.url, `http://${req.headers.host}`); // 输出 URL 的各个部分 res.end(util.inspect({ href: myUrl.href, origin: myUrl.origin, protocol: myUrl.protocol, host: myUrl.host, hostname: myUrl.hostname, port: myUrl.port, pathname: myUrl.pathname, search: myUrl.search, searchParams: Object.fromEntries(myUrl.searchParams) // 将 searchParams 转为普通对象 })); }).listen(3000); console.log("Server is running at http://localhost:3000");
在浏览器中访问 http://localhost:3000/user?name=菜鸟教程&url=www.runoob.com 然后查看返回结果:

获取 URL 的参数
我们可以使用 url.parse 方法来解析 URL 中的参数,代码如下:
实例
const http = require('http'); http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); // 使用 URL 构造函数解析请求 URL const myUrl = new URL(req.url, `http://${req.headers.host}`); // 获取查询参数 const name = myUrl.searchParams.get("name"); const siteUrl = myUrl.searchParams.get("url"); res.write("网站名:" + (name || "未提供")); res.write("\n"); res.write("网站 URL:" + (siteUrl || "未提供")); res.end(); }).listen(3000); console.log("Server is running at http://localhost:3000");
在浏览器中访问 http://localhost:3000/user?name=菜鸟教程&url=www.runoob.com 然后查看返回结果:

最低0.47元/天 解锁文章
574

被折叠的 条评论
为什么被折叠?



