微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Express学习笔记——request 和response

简介

Express的request可以用于获取前端传输过来的数据,而response则可以像前端返回数据,下面分别就接收前端数据和向前端返回数据的几个主要函数进行介绍。

Request

req.query

  1. 作用
  • 用于获取复杂的get请求
  • http请求中使用?作为请求参数和路由地址的分隔
  1. 用法
var express = require('express');
var app = express();
app.get('/test', function(){
    
});
  • 请求与结果如下:
// GET /test?q=tobi+@R_78_5023@
req.query.q
// => "tobi @R_78_5023@"

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

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

req.query.shoe.type
// => "converse"

req.params

  1. 作用
  1. 用法
var express = require('express');
var app = express();
app.get('/test/:username', function(){
    
});
  • 请求与结果如下
// GET /user/tj
req.params.name
// => "tj"

req.body

  1. 作用
  • 用于获取Post请求中的数据
  1. 用法
var app = require('express')();
var bodyParser = require('body-parser');


app.post('/login', function (req, res) {
  console.log(req.body);
  res.json(req.body);
});

Response

res.end

res.end([data] [, encoding])

作用:用于快速的结束响应,可以不包含任何数据

res.json

  1. 语法:
res.json([body])
  1. 作用:

返回一个JSON格式的响应(通过JSON.stringify()进行的格式转换)

res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });

res.redirect

  1. 语法
res.redirect([status,] path)
  1. 作用
  • 指向特定的URL
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login')

res.render

  1. 语法
res.render(view [, locals] [, callback])
  1. 作用
  • 渲染视图,并将其返回给客户端
  • local参数定义了返回的视图中需要使用的局部变量
  • 添加回调函数时,如果获取文件成功,才会在回调函数中进一步执行
// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

res.send

  1. 语法
res.send([body])
  1. 作用
  • 发送http响应
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' });

对比

  1. res.end/res.json/res.send
  • res.end 主要用于快速结束响应,可以不包含数据
  • res.json 用于返回JSON格式的数据
  • res.send 可以返回各类数据
  1. res.redirect/res.render
  • res.redirect 主要用于指向特定的URL,当URL是本地的视图文件时,效果和res.render相同

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐