GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — Node.js GET/POST请求 | 菜鸟教程
Node.js 教程
Node.js 教程
Node.js 概念
Node.js 安装配置
Node.js VS Code
Node.js NVM
Node.js 创建第一个应用
Node.js 工作机制
NPM 使用介绍
PNPM 使用介绍
Node.js REPL
Node.js 异步编程
Node.js 回调函数
Node.js Promise
Node.js async/await
Node.js 事件循环
Node.js EventEmitter
Node.js Buffer
Node.js Stream
Node.js 模块系统
Node.js 模块导入
Node.js 函数
Node.js 路由
Node.js 全局对象
Node.js 常用工具
Node.js 文件系统
Node.js 内置模块
Node.js 测验
Node.js 应用Node.js 构建简单应用 Node.js GET/POST请求 Node.js util 模块 Node.js Web 模块 Node.js Express 框架 Node.js RESTful API Node.js 多进程 Node.js JXcore 打包 Node.js MySQL Node.js MongoDB npx 入门教程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 然后查看返回结果:
URL 对象以下是 URL 对象的属性和方法:
实例
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 获取 POST 请求内容在 Node.js 中,处理 POST 请求通常需要通过 http 模块来接收请求体中的数据。POST 请求数据不像 GET 请求那样包含在 URL 中,而是作为请求体发送。因此,在 Node.js 中接收 POST 数据时,需要监听并处理 request 对象的 data 和 end 事件。
实例
const http = require('http'); // 创建 HTTP 服务器 http.createServer((req, res) => { // 检查请求方法是否为 POST if (req.method === 'POST') { let body = ''; // 监听 data 事件,逐块接收数据 req.on('data', (chunk) => { body += chunk; // 累加接收到的数据块 }); // 监听 end 事件,数据接收完毕 req.on('end', () => { // 输出接收到的 POST 数据 console.log('Received POST data:', body); // 设置响应头和内容 res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('POST data received successfully!'); }); } else { // 非 POST 请求的处理 res.writeHead(405, { 'Content-Type': 'text/plain' }); res.end('Only POST requests are supported.'); } }).listen(3000, () => { console.log('Server is running at http://localhost:3000'); }); 代码说明:
你可以使用 curl 命令来测试 POST 请求: curl -X POST -d "name=example&age=25" http://localhost:3000 处理 JSON 数据如果 POST 请求发送的是 JSON 数据,可以在 req.on('end') 中将接收的数据解析为对象: req.on('end', () => {
const parsedData = JSON.parse(body); // 将 JSON 字符串解析为对象
console.log('Received JSON data:', parsedData);
res.end('JSON data received successfully!');
});
querystring 模块querystring 模块用于处理 URL 查询字符串和 POST 请求的数据。 对于 application/x-www-form-urlencoded 编码的 POST 请求数据,querystring 模块可以帮助解析请求体,将它转换成 JavaScript 对象,方便访问和操作。 假设客户端发送的 POST 请求数据格式为 基本语法结构说明var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res){
// 定义了一个post变量,用于暂存请求体的信息
var post = '';
// 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
req.on('data', function(chunk){
post += chunk;
});
// 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
req.on('end', function(){
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);
以下实例表单通过 POST 提交并输出数据: 实例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);
执行结果 Gif 演示:
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |