NODEJS:立即发送文件和数据

时间:2013-09-18 05:26:21

标签: javascript node.js express

这就是我得到的。它工作得很好,但我希望能够在登录我的网站时向客户端发送文件和数据(JSON)。有没有办法把它结合起来?

app.get('/', function (req, res) { 
    res.sendfile(__dirname + '/index.html');
});

2 个答案:

答案 0 :(得分:1)

您不能一次发送2个文件。但是您可以使用带有ejs的模板库将JSON嵌入到html中。

答案 1 :(得分:0)

流只能为请求发送一种类型的内容。但是,根据您的Accept标头,您可以在同一请求网址上为不同的请求发送不同的内容

app.get('/', function (req, res) {      
    if(req.accepts('text/html')){
        res.sendfile(__dirname + '/index.html');
        return;
     }
     else if(req.accepts('application/json')){  
        res.json({'key':'value'});
        return;
     }
});

如果您的请求标头接受'text/html',则会返回index.html文件。如果请求标头接受'application/json',它将返回JSON响应。

相关问题