Nodejs(express) - 03 请求和响应

app.get('/', (req, res) => {})

路由函数参数req,res分别代表HTTP的请求数据和响应数据

一、request请求对象

  • req.query获取通过url(如?key=value)提供的参数。参数名可使用[]实现对象格式
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"

req.query.shoe.color
// => "blue"

req.query.shoe.type
// => "converse"
  • req.params获取命名路由中参数的值
app.route('/users/:userId', (req, res) => {
   console.log( req.params.userId )
})

访问 /users/0987, 将输出‘0987’

  • req.body获取请求body中的键值对
    req.body需要结合body-parser(普通键值对)或 multer(文件类)中间件使用
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

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

app.post('/profile', upload.array(), function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});

response响应对象

  • res.json()发送JSON对象
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
  • res.download()供客户端下载一个附件
    res.download(path [, filename] [, options] [, fn])
res.download('/report-12345.pdf');

res.download('/report-12345.pdf', 'report.pdf');

res.download('/report-12345.pdf', 'report.pdf', function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});
  • res.render() 渲染视图模板
    安装模板引擎
$ npm install pug --save

引擎加入到express
···
app.set('view engine', 'pug')
···
编写模板

html
  head
    title= title
  body
    h1= message

返回基于模板填充了实际数据的最终html

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})
  • res.send()发送一个复杂的HTTP请求
    send()函数可以发送多种响应,且会自动提供Head和http cache支持,如content-type
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' });

下面是res对象提供可向客户端发送响应的函数

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

你可能感兴趣的:(Nodejs(express) - 03 请求和响应)