使用 Express.js 傳送 HTTP 錯誤程式碼


我們可以根據使用者的需求透過 Express.js 應用程式端點發送不同的 HTTP 狀態和響應。在出現錯誤或請求被禁止的情況下,我們也可以傳送一條訊息。狀態程式碼200會隨返回的響應一起預設傳送。

語法

res.status( statusCode )

示例 1

建立一個名為“status.js”的檔案,並複製以下程式碼片段。在建立檔案後,使用命令“node status.js”執行此程式碼,如下面的示例所示 −

// Specifying status code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get("/api", (req, res) => {
   res.status(400);
   res.send("Bad Request Received")
})

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

使用 GET 請求點選以下 URL 端點 – localhost:3000/

輸出

Bad Request Received

示例 2

我們再看一個示例。

// Specifying status code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get("/api", (req, res) => {
   res.status(403);
   res.send("This API Endpoint is forbidden")
})

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

使用 GET 請求點選以下 URL 端點 – localhost:3000/

輸出

This API Endpoint is forbidden

更新於: 2022 年 3 月 28 日

861 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.