Express.js – res.set() 方法
res.set() 方法可用于将响应的 HTTP 标头字段设置为 value。你还可以将一个对象作为参数来一次性设置多个字段。
语法
res.set( field, [value] )
示例 1
创建一个名为 "resSet.js" 的文件并复制代码段。创建文件后,使用命令 "node resSet.js" 来运行此代码,如下例所示 −
// res.set(field, [value]) Method Demo Example
// Importing the express
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){
// Setting the response content-type
res.set({
'Content-Type': 'text/html'
});
// Checking if content-type is set
console.log("Content-Type is: ", res.get('Content-Type'));
res.end();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求访问以下端点 −
https://:3000/api
输出
C:\home
ode>> node resSet.js Server listening on PORT 3000 Content-Type is: text/html; charset=utf-8
示例 2
再看一个示例。
// res.set(field, [value]) Method Demo Example
// Importing the express
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.use('/api', function(req, res, next){
res.set({
'Content-Type': 'application/zip'
});
next();
})
// Using middleware
app.get('/api', function(req, res){
console.log("Content-Type is : ", res.get('Content-Type'));
res.end();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求访问以下端点 −
https://:3000/api
输出
C:\home
ode>> node resSet.js Server listening on PORT 3000 Content-Type is : application/zip
广告
数据结构
网络
关系型数据库系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP