返回介绍

Request 和 Response 对象

发布于 2025-04-26 18:09:28 字数 2480 浏览 0 评论 0 收藏

- Express 的 Request 和 Response 对象继承自 Node HTTP 的 Request 和 Response 对象:

// https://github.com/strongloop/express/lib/request.js 文件


var req = exports = module.exports = {
  __proto__: http.IncomingMessage.prototype
}

// https://github.com/strongloop/express/lib/response.js 文件


var res = module.exports = {
  __proto__: http.ServerResponse.prototype
}

- 使用 Node 的 HTTP 方法

我们可以直接在 Express 中使用 Node 的 write 和 end 方法:

var express = require('express');
var app = express();
app.get('/', function(request, response){
  response.write('Hello World');
  response.end();
});
app.listen(3000);

等同于这段代码:

var express = require('express');
var app = express();
app.get('/', function(request, response){
  response.send('Hello World');
});
app.listen(3000);

- 返回 JSON 数据

send 函数可以将对象和数据转换为 JSON 格式返回:

app.get('/todos', function(request, response) {
  var todos = ["Todo item 1", "Todo item 2", "Todo item 2"];
  response.send(todos);
});

在 curl 命令中添加-i 参数:

curl -i http://localhost:3000/todos

我们看到如下的返回信息:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8

["Todo item 1", "Todo item 2", "Todo item 2"]

- 返回 HTML 信息

send 函数可以识别 HTML 字符串并设置对应的响应头:

app.get('/blocks', function(request, response) {
  var blocks = '<ul><li>Todo item 1</li><li>Todo item 2</li></ul>';
  response.send(blocks);
});

使用 curl 来测试:curl -i http://localhost:3000/blocks。

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8

<ul><li>Todo item 1</li><li>Todo item 2</li></ul>

- 使用 redirect 设置合适的响应头来重定向到新的地址

app.get('/todos', function(request, response) {
  response.redirect('/parts');
});

使用 curl 来测试:curl -i http://localhost:3000/todos。

HTTP/1.1 302 Moved Temporarily
X-Powered-By: Express
Location: /parts
Content-Type: text/plain; charset=utf-8
!
Moved Temporarily. Redirecting to /parts

- 自定义重定向的状态码

函数的第一个参数会被解析为用于重定向的状态码:

app.get('/todos', function(request, response) {
  response.redirect(301, '/parts');
});

使用 curl 来测试:curl -i http://localhost:3000/todos。

HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Location: /parts
Content-Type: text/plain; charset=utf-8
!
Moved Permanently. Redirecting to /parts

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。