简体   繁体   中英

Node.js Express

I have an express server, and I would like to write something like

for(p in params)
    app.get("/"+p,function (req, res) {res.send(p)});

Now, for params[0], request arrives, but response is params[n-1]

You can use anonimous function to make copy of 'p' on each iteration.

var http = require('http');
var express = require('express');
var app = express();

var params = {
    'a' : 1,
    'b' : 2,
    'c' : 3
};

for (p in params) {
    (function (p) {
        app.get('/' + p, function (req, res) { res.send(p); });
    })(p);
}

http.createServer(app).listen(1339, '0.0.0.0');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM