1. 程式人生 > >express 學習筆記(二)request && response

express 學習筆記(二)request && response

Request:

1. req.params

2. req.query

3. req.body

4. req.files

5. req.param(id)

          param -> body -> query

6. req.cookies

7. req.header == req.get

Response:

1. res.render

2. res.locals

3. res.set

4.res.status

5. res.send([body]) 

6. res.json([body])

7.res.redirect

程式碼: (Request)

var express = require('express');
var bodyParser = require('body-parser');
var cookieParse = require('cookie-parser');
var app = express();

// request.body 用
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParse());

app.get('/', function (request, response, next) {
    console.log(request.query);
});

app.post('/test', function (request, response, next) {
    console.log(request.body);
    console.log(request.cookies);
    console.log(request.get("content-type"));
});

app.listen(1234, 'localhost');

程式碼: (Response)
var express = require('express');
var hbs = require('express-handlebars');
var app = express();

app.engine('hbs', hbs());
app.set('view engine', 'hbs');

app.get('/test', function (request, response, next) {
    response.locals = {
        name:'maizi'
    };
    next();
},function (request, response, next) {
    console.log(response.locals);
    response.set('Content-type', 'text/html');
    // response.render('render', {name:"maizi.edu"});
    response.render('render');//locals 會預設傳入
});

app.get('/send',function (request, response, next) {
    // response.send(404, 'Not Found');
    response.status(200).send('<p>Hello World! </p>');
});

app.get('/json',function (request, response, next) {
    response.status(200).send({
        name:'maizi',
        domin:'maizi.edu'
    });
});

app.get('/redirect',function (request, response, next) {
    // response.redirect('https://www.baidu.com');
    response.redirect('/json');
});

app.listen(1234, 'localhost');

render.hbs
<head></head>

<body>
  <h1> This is  {{name}} </h1>
</body>