资讯专栏INFORMATION COLUMN

Node.js学习之路26——Express的response对象

davidac / 377人阅读

摘要:如果包含字符则将设置为。添加字段到不同的响应头将该字段添加到不同的响应标头如果它尚未存在。

3. response对象 3.1 是否发送了响应头

res.headersSent布尔属性,app是否发送了httpheaders

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser")
const app = express();

app.use(bodyParser.json());// parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));// parsing application/x-www-form-urlencoded
app.use(cookieParser())

app.get("/", (req, res) => {
    console.log(res.headersSent); // false
    res.send("OK");
    console.log(res.headersSent); // true
})
app.listen(3000);
3.2 添加响应头信息

res.append(filed,[value])添加响应头信息

使用res.append()之后调用res.set()将会重置先前设置的头信息

const express = require("express");
const app = express();
app.get("/", (req, res) => {
    console.log(res.headersSent); // false
    res.append("Link", ["", ""]);
    res.append("Set-Cookie", "foo=bar; Path=/; HttpOnly");
    res.append("Warning", "199 Miscellaneous warning");
    res.attachment("path/to/logo.png");
    res.cookie("user", { name: "Jack", age: 18 });
    res.cookie("maxAge", 1000 * 60 * 60 * 24 * 30);
    res.send("OK");
    console.log(res.headersSent); // true
})
app.listen(3000);
3.3 设置HTTP响应Content-Disposition字段attachment

res.attachment([filename])

设置HTTP响应Content-Disposition字段attachment

如果参数为空,那么设置Content-Disposition:attachment

如果参数有值,那么将基于res.type()扩展名设置Content-Type的值,并且设置Content-Disposition的值为参数值

res.attachment();
// Content-Disposition: attachment

res.attachment("path/to/logo.png");
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png

3.4 设置cookie信息

res.cookie(name, value, [options])

清除cookie信息res.clearCookie(name, [options])

设置cookienamevalue,value值可以是stringobject,options是一个对象

domain,string,cookie的域名,默认为该app的域名

expires,date,过期时间

httpOnly,boolean,cookie的标志位,只能允许http web server

maxAge,string,用于设置过期时间相对于当前时间 (以毫秒为单位) 的选项.

path,string,cookie的路径,默认为/

secure,boolean,标记只用于HTTPScookie.

signed,boolean,指示是否应对cookie进行签名.(有问题,需要cookie-parser)

所有的res.cookie ()都是用所提供的选项设置HTTP设置cookie头.任何未指定的选项都默认为RFC 6265中所述的值.
使用cookie-parser中间件时, 此方法还支持签名的cookie.只需将签名的选项设置为 true.然后,res cookie ()将使用传递给cookieParser(秘密) 的秘密来签署该值.
3.5 响应下载信息

res.download(path, [filename], [callback(err){...}])

const express = require("express");
const app = express();
app.get("/", (req, res) => {
    res.download("static/download/file.pdf", "file.pdf", (err) => {
        if (err) {
            res.send(err);
        }
    });
})
app.listen(3000);
3.6 结束响应进程

res.end([data], [encoding])

不需要返回任何数据,如果需要返回数据,可以使用res.send()或者res.json()

3.7 获取请求头信息

res.get(field)

通过字段返回HTTP请求头信息,大小写敏感

res.get("Content-Type");
// => "image/png"
3.8 发送一个JSON响应

res.json([body])

方法类似于带有一个对象参数或数组参数的res.send()

参数也可以为null或者undefined

res.json(null)
res.json({ user: "tobi" })
res.status(500).json({ error: "message" })
3.9 填充响应的链接HTTP标题头字段

res.links(links)

res.links({
    next: "http://localhost:3000/users?page=2",
    next: "http://localhost: /users?page=5"
})
3.10 响应重定向

res.redirect([status], path)

如果不指定status状态,默认状态码status code302 Found

如果要跳转到外部的链接,需要加上http://

返回上一步的页面res.redirect("back");

返回上一级的页面,如果现在是在http://example.com/admin/post/new页面,想要跳转到上一级页面http//example.com/admin/post,使用res.redirect("..");

res.redirect("/users");
res.redirect(301, "http://localhost:3000/login")
3.11 渲染模板引擎

res.render(view, [locals], [callback(err,html){...}])

模板引擎一般有ejs,jade,html

3.12 发送HTTP响应信息

res.send([body])

参数可以是String,Buffer,Array

res.send(new Buffer("whoop"));
res.send({ some: "json" });
res.send("

some html

"); res.status(404).send("Sorry, we cannot find that!"); res.status(500).send({ error: "something blew up" });
3.13 给定路径上传输文件

res.sendFile(path, [options], [callback(err){...}])

根据文件名的扩展名设置内容类型响应HTTP标头字段.除非在选项对象中设置了根选项, 否则路径必须是文件的绝对路径.

options是一个对象选项

maxAge,以毫秒为单位设置Cache-Control标题头的最大属性或ms格式的字符串,默认为0

root,相对文件名的根目录

lastModified,将Last-Modified的标题头设置为操作系统上文件的最后修改日期.设置为false以禁用它.

headers,包含要与文件一起服务的HTTP标头的对象.

dotfiles,服务dotfiles的选项.可能的值是allow,deny,ignore,默认值为ignore

router.get("/file/:name", (req, res, next) => {
    let options ={
        root: "./public/static/download/",
        dotfiles: "deny",
        headers: {
            "x-timestamp": Date.now(),
            "x-sent": true
        }
    };
    
    let fileName = req.params.name;
    res.sendFile(fileName, options, (err) => {
        if(err){
            console.log(err);
            res.status(err.status).end();
        }else{
            console.log("Sent: ",fileName)
        }
    })
});
3.14 设置状态代码

res.sendStatus(statusCode)

将响应HTTP状态代码设置为statusCode, 并将其字符串表示形式作为响应正文发送.

res.sendStatus(200); // equivalent to res.status(200).send("OK")
res.sendStatus(403); // equivalent to res.status(403).send("Forbidden")
res.sendStatus(404); // equivalent to res.status(404).send("Not Found")
res.sendStatus(500); // equivalent to res.status(500).send("Internal Server Error")
3.15 设置响应头信息

res.set(field, [value])

可以单个设置,也可以用一个对象设置

res.set("Content-Type", "text/plain");

res.set({
  "Content-Type": "text/plain",
  "Content-Length": "123",
  "ETag": "12345"
})
3.16 设置响应状态

res.status(code)

使用此方法可设置响应的HTTP状态.它是节点响应的式别名statusCode

res.status(403).end();
res.status(400).send("Bad Request");
res.status(404).sendFile("/absolute/path/to/404.png");
3.17 设置响应类型

res.type(type)

将内容类型HTTP标头设置为指定类型的mime.lookup()所确定的mime类型。如果type包含/字符, 则将Content-Type设置为type

res.type(".html");              // => "text/html"
res.type("html");               // => "text/html"
res.type("json");               // => "application/json"
res.type("application/json");   // => "application/json"
res.type("png");                // => "image/png:"
3.18 添加字段到不同的响应头

res.vary(filed)

将该字段添加到不同的响应标头 (如果它尚未存在)。

res.vary("User-Agent").render("docs");

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/93057.html

相关文章

  • Node.js学习之路27——Expressrouter对象

    摘要:对象大小写敏感默认不敏感保留父路由器的必需参数值如果父项和子项具有冲突的参数名称则该子项的值将优先激活严格路由默认禁用禁用之后正常访问但是不可以访问全部调用或者或者实际上就是的各种请求方法使用路由使用模块方法 Router([options]) let router = express.Router([options]); options对象 caseSensitive,大小写敏...

    NicolasHe 评论0 收藏0
  • Node.js学习之路25——Expressrequest对象

    摘要:对象表示请求并且具有请求查询字符串参数正文标题头等属性对应用程序实例的引用保存了很多对使用中间件的应用程序实例的引用挂载在路由实例上的路径请求主体和和包含在请求正文中提交的数据的键值对默认情况下它是未定义的当您使用体解析中间件如和时将被填 2. request req对象表示http请求,并且具有请求查询字符串,参数,正文,http标题头等属性 app.get(/user/:id, ...

    cocopeak 评论0 收藏0
  • Node.js学习之路24——Express框架app对象

    1.express() 基于Node.js平台,快速、开放、极简的web开发框架。 创建一个Express应用.express()是一个由express模块导出的入口top-level函数. const express = require(express); let app = express(); 1.1 静态资源管理 express.static(root, [options]) expr...

    smallStone 评论0 收藏0
  • Node.js 中度体验

    摘要:创建简单应用使用指令来载入模块创建服务器使用方法创建服务器,并使用方法绑定端口。全局安装将安装包放在下。的核心就是事件触发与事件监听器功能的封装。通常我们用于从一个流中获取数据并将数据传递到另外一个流中。压缩文件为文件压缩完成。 创建简单应用 使用 require 指令来载入 http 模块 var http = require(http); 创建服务器 使用 http.create...

    CastlePeaK 评论0 收藏0
  • Node.js学习之路23——Node.js利用mongoose连接mongodb数据库

    摘要:类比一下你有一个巨型停车场,里边分了不同的停车区集合,这里的,每个停车区可以停很多车下文提到的,相当于每个数据集合里边可以有很多张数据表。 Node.js利用mongoose连接mongodb数据库 Node.js连接mongodb数据库有很多种方法,通过mongoose模块引入是其中的一个方法 代码组织结构 |---|根目录 |---|---|connect.js(mongoose测...

    ssshooter 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<