Express.js – app.post() 方法
app.post() 方法将所有 HTTP POST 请求路由到指定的路径,并使用指定的回调函数。
语法
app.path(path, callback, [callback])
参数
- path − 这是触发中间件函数的路径。路径可以是字符串、路径模式、正则表达式或这些内容的数组。
- callback − 这些是中间件函数或一系列中间件函数,它们的作用就像中间件,只不过这些回调可以调用 next(路由)。
示例 1
创建一个名为 "appPost.js" 的文件,然后复制以下代码片段。创建文件后,可以使用命令 "node appPost.js" 来运行此代码。
// app.post() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a POST request
app.post('/api', (req, res) => {
console.log("POST Request Called for /api endpoint")
res.send("POST Request Called")
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 POST 请求访问以下端点
https://:3000/api
输出
C:\home
ode>> node appPost.js Server listening on PORT 3000 POST Request Called for /api endpoint
示例 2
我们来看另一个示例。
// app.post() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a POST request
app.post('/api', (req, res) => {
console.log("Method called is -- ", req.method)
res.end()
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});现在,使用 POST 请求访问以下端点
https://:3000/api
输出
C:\home
ode>> node appPost.js Server listening on PORT 3000 Method called is -- POST
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP