Nodejs(express) - 03 请求和响应

2019-11-21  本文已影响0人  Lisa_Guo
app.get('/', (req, res) => {})

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

一、request请求对象

// 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"
app.route('/users/:userId', (req, res) => {
   console.log( req.params.userId )
})

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

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(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
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.
  }
});
$ 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(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
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.
上一篇 下一篇

猜你喜欢

热点阅读