0

我正在使用 NodeJS 和 ExpressJS 为简单的后端实现 RESTful API 服务器。我也在使用 BackboneJS 在前面渲染视图。因此,现在我有一个 index.html 文件,我想在客户端向“/”路由发送 /GET 时呈现该文件。这是我到目前为止所拥有的:

var express = require('express');
var app = express();
app.use(express.bodyParser());
var mongo = require('mongodb');
var mongoose = require('mongoose');

var Server = mongo.Server, 
    DB = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});


db = new DB('mydb', server, {safe: true});

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'mydb' database");
        db.collection('items', {safe:true}, function(err, collection) {
            if (err) {
                console.log("Creating collection 'items'");
            }
        });
    }
});

var port = process.env.PORT || 3000;

app.engine('.html');

var listItems = function(req, res){
    db.collection('items', function(err, collection){
        var items = collection.find();
        console.log(items);
        res.send(items);
    });
}

var itemDetails = function(req, res){

}

var deleteItem = function(req, res){

}

var createItem = function(req, res){

}

var updateItem = function(req, res){

}

var routeHome = function(req, res){

        // What can I do here to render a plain .html file?

}

app.all('*', function(req, res, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Content-Type", "application/json");
    next();
});

app.get('/', routeHome);

app.get('/items', listItems);
app.get('/items/:id', itemDetails);
app.del('/users/:id', deleteItem);
app.post('/users', createItem);
app.put('/users/:id', updateItem);

app.listen(port);

console.log("Server started up on port " + port);

正如您所看到的,我已经完成了所有设置,除了我无法弄清楚如何将常规 .html 文件发送到客户端。我不需要渲染引擎,因为 Backbone 正在为我做这一切。我只想让 index.html 去客户端。

4

2 回答 2

1

只使用express.static中间件怎么样?由于您使用的是 Backbone,您可能还需要发送静态 JS 文件:

app.use(express.static(__dirname));

Place that somewhere before your other routes. It will try and find files requested in __dirname (the directory where your app.js file resides, but you can of course change the location where the middleware will try and find files), including index.html.

于 2013-03-08T09:09:14.640 回答
0

Step One, Remove app.engine(".html"),

Step Two:

var routeHome = function(req, res){
    // Do What Ever
    res.sendFile("index.html",function(err){ // Transfer The File With COntent Type Text/HTML
        if(err){
            res.end("Sorry, Error.");
        }else{
            res.end(); // Send The Response
        }
    })
}
于 2013-03-09T14:41:34.790 回答