Express.js – res.get() 方法
res.get() 方法用来返回由字段指定的 HTTP 头。匹配不区分大小写,因此返回具有所有匹配模式的头。
语法
res.get( field )
例子 1
创建名为 “resGet.js” 的文件,复制代码段。在创建文件后,使用命令 “node resGet.js” 运行此代码,如下例所示:
// res.get(field) 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){
// Setting the Content-type
res.set({
'Content-Type': 'application/json',
});
// "text/plain"
console.log(res.get('Content-Type'));
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 resGet.js Server listening on PORT 3000 application/json; charset=utf-8
例子 2
让我们再看一个例子。
// res.get(field) 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.use('/api', function(req, res, next){
//Setting the response
res.set({
'Content-Type': 'application/xml',
});
next();
})
app.get('/api', function(req, res){
console.log("Content-Type is: ", res.get('Content-Type'));
res.send();
});
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 resGet.js Server listening on PORT 3000 Content-Type is: application/xml
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP