在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。
表单提交到服务器一般都使用 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");
const myUrl = new URL("http://example.com/path?foo=bar&hello=world");
console.log(myUrl.pathname); // 输出: /path
console.log(myUrl.searchParams.get("foo")); // 输出: bar
myUrl.searchParams.append("newKey", "newValue");
console.log(myUrl.href); // 输出: http://example.com/path?foo=bar&hello=world&newKey=newValue
querystring 模块
querystring 模块用于处理 URL 查询字符串和 POST 请求的数据。
对于 application/x-www-form-urlencoded 编码的 POST 请求数据,querystring 模块可以帮助解析请求体,将它转换成 JavaScript 对象,方便访问和操作。
假设客户端发送的 POST 请求数据格式为 application/x-www-form-urlencoded
(例如表单提交),数据形式类似于 name=example&age=25
。在接收到数据后,可以使用 querystring.parse
方法将数据解析成对象。
var http = require('http');
var querystring = require('querystring');
var postHTML =
'<html><head><meta charset="utf-8"><title>菜鸟教程 Node.js 实例</title></head>' +
'<body>' +
'<form method="post">' +
'网站名: <input name="name"><br>' +
'网站 URL: <input name="url"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// 解析参数
body = querystring.parse(body);
// 设置响应头部信息及编码
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url) { // 输出提交的数据
res.write("网站名:" + body.name);
res.write("<br>");
res.write("网站 URL:" + body.url);
} else { // 输出表单
res.write(postHTML);
}
res.end();
});
}).listen(3000);
点击"提交"按钮后,显示如下: