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