Express.js – res.end() 方法
res.end() 方法結束了當前響應程序。此方法用於在沒有任何資料的情況下快速結束響應。如果需要使用資料進行響應,則應該使用 res.send() 方法或 res.json() 方法。
語法
res.end([data], [encoding])
預設編碼為 'utf-8'。
示例 1
建立一個名為 "resEnd.js" 的檔案,並複製以下程式碼片段。建立檔案後,使用如下所示的命令 "node resend.js" 來執行此程式碼 −
// res.end() Method Demo Example
// Importing the express module
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("Ending the process without any data");
res.end();
});
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 resEnd.js Server listening on PORT 3000 Ending the process without any data
示例 2
我們來看看另一個示例。
// res.end() Method Demo Example
// Importing the express module
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("Ending the process without any data");
res.end();
res.send("Data sent after ending the process");
});
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 resEnd.js Server listening on PORT 3000 Ending the process without any data Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (/home/node/test/node_modules/express/lib/response.js:771:10) at ServerResponse.contentType (/home/node/test/node_modules/express/lib/response.js:599:15) at ServerResponse.send (/home/node/test/node_modules/express/lib/response.js:145:14) at /home/node/test/express.js:16:6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP