使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP