标签归档:express

node.js – Difference between app.use and app.get in express.js

http://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js

app.use() is intended for binding middleware to your application. The path is a “mount” or “prefix” path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...

By specifying / as a “mount” path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
etc.
app.get(), on the other hand, is part of Express’ application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:
GET /
And, the equivalent routing for your example of app.use() would actually be:

app.all(/^/.*/, function (req, res) {
    res.send('Hello');
});

Node.js使用express解析cookie

首先使用cookieParser()解析请求头里的Cookie, 并用cookie名字的键值对形式放在 req.cookies 你也可以通过传递一个secret 字符串激活签名了的cookie 。
app.use(express.cookieParser());
app.use(express.cookieParser('some secret'));

下面是读写cookie的代码


var express = require('express');
var app = express();
app.get('/readcookie',function(req,res){
    res.send('req.cookies.name:' + req.cookies.name);
});
app.get('/writecookie',function(req,res){
    res.cookie('name', 'I'm a cookie', 60000);
    res.send("cookie saved");
});
app.listen(3000);
console.log('listening on port 3000');