res.location() 方法在 Express.js 中


res.location() 方法用于将响应的位置 HTTP 标头设置为指定的 path 参数。设置位置并不会结束进程,设置位置标头后还是可以发送一些响应。

语法

res.location( path )

示例 1

创建一个名为 "resLocation.js" 的文件,并复制以下代码段。创建文件后,使用命令 "node resLocation.js" 来运行此代码,如下面的示例所示 −

// res.location(path) 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){
   res.location('https://tutorialspoint.com');
   console.log(res.get('location')); //
   https://tutorialspoint.com
   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 resLocation.js Server listening on PORT 3000 https://tutorialspoint.com

示例 2

我们来看另一个示例。

// res.location(path) 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){
   res.location('/v1/users/profile');
   console.log("Location Path is: ", res.get('location')); //
   https://tutorialspoint.com
   res.send(res.get('location'));
});
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 resLocation.js Server listening on PORT 3000 Location Path is: /v1/users/profile

更新日期: 2022 年 1 月 29 日

734 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告栏
© . All rights reserved.