常用的返回方式有四种 res.json([status|body], [body]) 以json的形式返回数据 res.render(view [, locals] [, callback]) 返回对应的view和数据,此方法可以有回调函数,以处理可能出现的异常 res.send([body|status], [body]) 返回自定义的数据,比如json或者404等状态 res.redirect([status,] path) 这个方法其实不是返回,而是跳转到另外一个url上 res.json([status|body], [body]) 官方文档: 返回一个 JSON 响应。 当res.send() 的参数是一个对象或者数组的时候, 会调用这个方法。 当然它也在复杂的空值(null, undefined, etc)JSON转换的时候很有用, 因为规范上这些对象不是合法的JSON。 res.json(null)res.json({ user: 'tobi' })res.json(500, { error: 'message' }) 适用情况:如果你用ajax请求,可以使用此方法做返回 res.render(view [, locals] [, callback]) 官方文档: 渲染view, 同时向callback 传入渲染后的字符串。 callback如果不传的话,直接会把渲染后的字符串输出至请求方, 一般如果不需要再对渲染后的模板作操作,就不需要传callback。 当有错误发生时next(err)会被执行. 如果提供了callback参数,可能发生的错误和渲染的字符串都会被当作参数传入, 并且没有默认响应。 res.render('index', function(err, html){ // ...});res.render('user', { name: 'Tobi' }, function(err, html){ // ...}); 适用情况:不适用ajax,直接访问此url,获取返回值和模板,填充对应模板数据 res.send([body|status], [body]),它可以返回自定义的属性 当参数为一个 Buffer时 Content-Type 会被设置为 “application/octet-stream” 除非它之前有像下面的代码: res.set('Content-Type', 'text/html');res.send(new Buffer('some html')); 当参数为一个String时 Content-Type 默认设置为”text/html”: res.send('some html'); 当参数为 Array 或者 Object 时 Express 会返回一个 JSON : res.send({ user: 'tobi' })res.send([1,2,3]) 最后一条当一个Number 作为参数, 并且没有上面提到的任何一条在响应体里, Express会帮你设置一个响应体 比如200 会返回字符”OK”, 404会返回”Not Found”等等. res.send(200)res.send(204)res.send(500) 适用情况:当你需要返回自定义属性时 res.redirect([status], url) 举例说,当你添加了一个帖子,返回一个帖子的id,然后又想直接打开帖子的内容,这个就有了用途,它会跳转到对应的url上,就是重定向 官方文档: Redirects to the URL dervied from the specified path, with specified HTTP status code status. If you don’t specify status, the status code defaults to “302 “Found”. 翻译: 重定向到从指定的路径的URL,与指定的HTTP状态代码状态。如果不指定状态,该状态代码默认为302。 res.redirect('/foo/bar');res.redirect('http://example.com');res.redirect(301, 'http://example.com');res.redirect('../login');