Express.js – 在方法中使用 app.METHOD()


app.METHOD() 用于映射或路由 HTTP 请求,其中的 METHOD 表示该请求的 HTTP 方法,例如 GET、POST、PUT 等,但为小写形式。因此,这些方法是 app.get()、app.post()、app.get() 等。

语法

app.METHOD(path, callback, [callback])

参数

  • path − 这是调用中间件函数的路径。路径可以是字符串、路径模式、正则表达式或所有这些项的数组。

  • callback − 这是中间件函数或一系列中间件函数,除了这些回调可以调用后面(路由)之外,这些函数的作用就像中间件。

示例 1

创建一个文件 "appMethod.js" 并复制以下代码片段。创建文件后,使用命令 "node appMethod.js" 运行此代码。

// app.METHOD() 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;

// This api will handle the GET request
app.get('/api', function(req, res){
   res.send("GET method called");
});

// This api will handle the POST request
app.post('/api', function(req, res){
   res.send("POST method called");
});

// This api will handle the PUT request
app.put('/api', function(req, res){
   res.send("PUT method called");
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

访问以下端点以获取响应

输出

C:\home
ode>> node appMethod.js Server listening on PORT 3000

在浏览器中,您将看到以下输出

更新日期:2021-10-01

378 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.