该方法使用指定的回调函数将所有 HTTP POST 请求路由到指定路径。app.post()
app.path(path, callback, [callback])
path -这是调用中间件函数的路径。路径可以是字符串、路径模式、正则表达式或所有这些的数组。
callback -这些是中间件函数或一系列中间件函数,它们的作用类似于中间件,但这些回调可以调用 next(路由)。
创建一个名为“ appPost.js ”的文件并复制以下代码片段。创建文件后,使用命令“ node appPost.js ”运行此代码。
// app.post() 方法演示示例 // 导入 express 模块 const express = require('express'); // 初始化 express 和端口号 var app = express(); // 从 express 初始化路由器 var router = express.Router(); var PORT = 3000; // 创建 POST 请求 app.post('/api', (req, res) => { console.log("POST Request Called for /api endpoint") res.send("POST Request Called") }) // 应用程序侦听以下端口 app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
使用 POST 请求命中以下端点
http://localhost:3000/api输出结果
C:\home\node>> node appPost.js Server listening on PORT 3000 POST Request Called for /api endpoint
让我们再看一个例子。
// app.post() 方法演示示例 // 导入 express 模块 const express = require('express'); // 初始化 express 和端口号 var app = express(); // 从 express 初始化路由器 var router = express.Router(); var PORT = 3000; // 创建 POST 请求 app.post('/api', (req, res) => { console.log("Method called is -- ", req.method) res.end() }) // 应用程序侦听以下端口 app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
现在,使用 POST 请求点击以下端点
http://localhost:3000/api输出结果
C:\home\node>> node appPost.js Server listening on PORT 3000 Method called is -- POST