Express - 使用响应对象

每个路由函数或中间件都接收一个response响应对象,路由函数通过调用响应对象的方法,可以将响应发送到客户端,并结束请求处理。 如果路由函数未调用响应对象的任何方法,则客户端请求将被挂起,直到客户端超时。

1. 设置响应状态码

resp.status(statusCode)

app.get('/', (req, resp) => {
  resp.status(403).end();
});

2. 设置响应报头

resp.set(field[, value])
resp.set({field:value})

app.get('/', (req, resp) => {
  resp.set('Content-Type', 'text/plain');
  resp.send('Hello, world');
});

2. 下载文件

resp.download(path[, filename][, options][, callback])

app.get('/download', (req, resp) => {
  resp.download('./data.pdf', 'data.pdf', (err) => {
    if(err){
      console.warn('download field', err);
    }
  });
  resp.send('Hello, world');
});

3. 结束响应过程

resp.end([chunk][, encoding][, callback])

app.get('/', (req, resp) => {
  resp.end('Hello, World');
});

4. 重定向url

resp.redirect([status,] path) //status: 301,302

app.get('/user/home', (req, resp) => {
  resp.redirect('/user/login');
});

5. 渲染Html模版页面

resp.render(view[, locals][, callback])

app.get('/user/home', (req, resp) => {
  resp.render('/user/home', {name: 'leon'});
});

6. 设置cookie

resp.cookie(name, value[, options])
options支持的选项

  • domain: 域名,默认为当前域名
  • expires GMT: 到期时间,如果未设置或设置为0,浏览器关闭后Cookie失效
  • httpOnly: 将Cookie标记为只有http服务器能访问,客户端js无法访问
  • maxAge: 以毫秒为单位的过期时间。通常比expires选项使用方便
  • path: Cookie路径
  • secure: 标记为仅在HTTPS协议下才发送
  • signed: 是否对Cookie签名
app.get('/', (req, resp) => {
  resp.cookie('logged', 'true', {
    httpOnly: true,
    maxAge: 24*3600*1000
  })
  .end();
});

7. 发送Http响应

resp.send([body])
body 响应内容支持string, Buffer, Object, Array.

  • String: Content-Type 将自动设置为text/html.
  • Buffer: Content-Type 将自动设置为application/octet-stream.
  • Object 或者 Array: Content-Type 将自动设置为application/json.
app.get('/', (req, resp) => {
  resp.send('Hello World');
});

app.get('/', (req, resp) => {
  resp.send({name: 'leon'});
});
posted @ 2022-02-20 21:44  箫笛  阅读(149)  评论(0)    收藏  举报