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',['
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)将字段添加到不同的响应头(如果它不存在)。水库变化('用户代理')。渲染('文档');