当前位置: 首页 > 后端技术 > Node.js

Node.js学习之路26-Express响应对象

时间:2023-04-03 15:25:02 Node.js

3.响应对象3.1是否发送响应头res.headersSent布尔属性,app是否发送http头constexpress=require('express');constbodyParser=require('body-parser');constcookieParser=require('cookie-parser')constapp=express();app.use(bodyParser.json());//解析application/jsonapp.use(bodyParser.urlencoded({extended:true}));//解析application/x-www-form-urlencodedapp.use(cookieParser())app.get('/',(req,res)=>{console.log(res.headersSent);//falseres.send('OK');console.log(res.headersSent);//true})app.listen(3000);3.2添加响应头信息res.append(filed,[value])使用res.append()添加响应头信息后调用res.set()会重置之前设置的头信息constexpress=require('express');constapp=express();app.get('/',(req,res)=>{console.log(res.headersSent);//falseres.append('Link',['','']);res.append('Set-Cookie','foo=bar;Path=/;HttpOnly');res.append('警告','199失误蜂窝状警告');res.attachment('path/to/logo.png');res.cookie('user',{name:'Jack',age:18});res.cookie('maxAge',1000*60*60*24*30);res.send('确定');控制台日志(res.headersSent);//真})app.listen(3000);3.3设置HTTP响应Content-Disposition字段attachmentres。attachment([filename])设置HTTP响应的Content-Disposition字段attachment如果参数为空,则设置Content-Disposition:attachment如果参数有值,则Content-Type的值会根据res设置。type()扩展,并设置Content-Disposition的值为参数值res.attachment();//Content-Disposition:attachmentres.attachment('path/to/logo.png');//Content-Disposition:依恋;filename="logo.png"//Content-Type:image/png3.4设置cookie信息res.cookie(name,value,[options])清除cookie信息res.clearCookie(name,[options])设置cookie名称和value,valuevalue可以是string或object,options是objectdomain,string,cookie域名,默认是app的域名expires,date,过期时间,string,用于设置过期时间相对于当前时间的选项(以毫秒为单位)。path,string,cookie路径,默认为/secure,boolean,flag仅用于Hcookie.signed用于TTPS,布尔值,表示是否应该对cookie进行签名。(有问题,需要cookie解析器)所有res.cookie()都是使用提供的选项设置HTTPsetcookie标头。任何未指定的选项默认为RFC6265中描述的值。当使用cookie-parser中间件时,此方法还支持签名cookie。只需将signed选项设置为true。然后,rescookie()将使用传递给cookieParser(secret)的秘密对值进行签名。3.5响应下载信息res.download(path,[filename],[callback(err){...}])constexpress=require('express');constapp=express();app.get('/',(req,res)=>{res.download('static/download/file.pdf','file.pdf',(err)=>{if(err){res.send(错误);}});})app.listen(3000);3.6结束响应过程res.end([data],[encoding])不需要返回任何数据,如果需要返回数据,可以使用res.send()或res.json()3.7获取请求头informationres.get(field)通过字段返回HTTP请求头信息,区分大小写res.get('Content-Type');//=>"image/png"3.8发送JSON响应。res.json([body])方法类似于带有对象参数或数组参数的res.send()。参数也可以为null或undefinedres.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,默认状态码为302如果你想找到跳转到外部链接,需要添加http://返回上一页res.redirect('back');返回上一页,如果现在是在http://example.com/admin/post/新页面,如果想跳转到上一页http//example.com/admin/post,使用res.redirect('..');res.redirect('/用户');res.redirect(301,'http://localhost:3000/login')3.11渲染模板引擎res.render(view,[locals],[callback(err,html){...}])模板引擎一般包括ejs,玉石,html3。12发送HTTP响应信息res.send([body])参数可以是String,Buffer,Arrayres.send(newBuffer('whoop'));res.send({some:'json'});res.send('

somehtml

');res.status(404).send('抱歉,我们找不到那个!');res.status(500).send({error:'somethingblownup'});3.13Transferafileonthegivenpathres.sendFile(path,[options],[callback(err){...}])根据文件名的扩展设置内容类型响应HTTP头域。除非在options对象中设置了root选项,否则路径必须是文件的绝对路径。options是一个对象选项maxAge,设置Cache-Control头的maximum属性,单位为毫秒或ms格式的字符串。默认为0root,相对于文件名根目录lastModified,将Last-Modified头设置为文件在操作系统上的最后修改日期。设置为false以禁用It.headers,一个包含与file.dotfiles一起服务的HTTP标头的对象,用于服务点文件的选项。可能的值有allow,deny,ignore,defaultignorerouter.get('/file/:name',(req,res,next)=>{letoptions={root:'./public/static/download/',dotfiles:'deny',headers:{'x-timestamp':Date.now(),'x-sent':true}};letfileName=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,表示为字符串Formsentasresponsetext.res.sendStatus(200);//相当于res.status(200).send('OK')res.sendStatus(403);//相当于res.status(403).send('Forbidden')res.sendStatus(404);//相当于res.status(404).send('NotFound')res.sendStatus(500);//等同于res.status(500).send('InternalServerError')3.15设置响应头信息res.set(fi字段,[值])可以单独设置或与对象一起设置res.set('Content-Type','text/plain');res.set({'Content-Type':'text/plain','Content-Length':'123','ETag':'12345'})3.16设置响应状态res.status(code)使用该方法设置响应的HTTP状态。是节点响应的别名statusCodes.status(403).end();res.status(400).send('BadRequest');res.status(404).sendFile('/absolute/path/to/404.png');3.17设置响应类型res.type(type)将Content-TypeHTTP标头设置为由指定类型的mime.lookup()确定的mime-type如果类型包含/字符,则设置Content-打字打字。res.type('.html');//=>'文本/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.vari(filed)将字段添加到不同的响应头(如果它不存在)。水库变化('用户代理')。渲染('文档');