2

I am using node.js at the server with express.js for some rest calls, my client side is uses backbone.js for the models and views. I am using underscore.js for templating some small html code for the views with backbone.

I have a designed a simple login module which uses a rest call to validate the user, once validated I show the after login page to the user.

Now in the javascript that I have written for the application, there are a few places where i need to include a random number in the url which is generated on user validation and returned to the client side.

So let me make it more clear by writing down the steps 1. Client sees the login page, enters user id and password 2. Server generates a token and sends it back to the client 3. All subsequent calls for further services include this token as a path parameter.

I am trying a solution where in I am trying to template the app.js javascript file and serve it using express.get below is the test code that i am trying as of now, just to prove the concept.

app.get('/js/:filename', function(req, res)
{
    console.log();
    var fname = process.env.PWD + "/public/js/" + req.params.filename;
    var obj =
    {
        user : req.session.user
    };
    fs.readFile(fname, function(err, data)
    {
        if (!err)
        {
            var returnstring = _und.template(data, obj);
            res.send(returnstring);
        }
    });

});

I am trying this with a very simple file(test.js) as of now

var a = '<%- user %>';

Whenever I am trying to template this and get it in the response, I am querying this using http://localhost:5555/js/test.js, I am getting the exact same in the response and not the user value that is set in the session.

I would be grateful for any help with this or any other solution that might exist that I can try with node.js, i.e some other templating library etc.

4

1 回答 1

2

对于上述问题,我深表歉意,似乎可以使用 javascript 模板化 javascript 文件 :) 。我只需要重新审视这个问题。刚改了这条线

fs.readFile(fname, function(err, data)

fs.readFile(fname, 'utf-8' , function(err, data)

它在那之后起作用。

实际问题在于我正在检索的数据,它不是作为字符串而是作为缓冲区出现,根据节点 js api,如果未指定文件类型,它将返回一个缓冲区。如果它被指定,那么它将给出一个字符串。就这样:)

于 2013-04-19T05:00:05.153 回答