Express.js 中的 req.method 属性
req.method 属性包含对应于请求的 HTTP 方法的字符串,这些方法是 GET、POST、PUT、DELETE,等等...
这些方法基于用户发送的请求。所有上述方法都有不同的用例。
语法
req.method
示例 1
创建一个名为 "reqMethod.js" 的文件并复制以下代码片段。创建文件后,使用命令 "node reqMethod.js" 运行此代码,如下例所示 −
// req.method Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an Endpoint
app.get('/api', function (req, res) {
console.log(req.method);
res.send(req.method);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求访问以下端点localhost:3000/api
输出
C:\home
ode>> node reqMethod.js Server listening on PORT 3000 GET
示例 2
让我们看另一个示例。
// req.method Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining multiple Endpoint
app.get('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.post('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.put('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});依次访问以下端点 −
GET 请求 −localhost:3000/api
POST 请求 −localhost:3000/api
PUT 请求 −localhost:3000/api
输出
C:\home
ode>> node reqMethod.js Server listening on PORT 3000 Request Method is: GET Request Method is: POST Request Method is: PUT
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP