【问题标题】:Index file being returned for all requests为所有请求返回索引文件
【发布时间】:2013-11-29 03:55:08
【问题描述】:

我对 Web 开发比较陌生。我正在使用节点(带快递)和角度 JS。虽然解决方案可能很简单,但我无法确定为什么每个请求的文件 (css/javascript/html) 的内容都与我的 index.html 文件的内容一起返回。

以下来自 chrome 检查器的屏幕截图说明了该问题:

controller.js 文件的内容显示的实际上是 index.html 文件的内容。

您可以从屏幕截图中的索引文件中看到相关内容。以下是节点服务器代码:

/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    api = require('./routes/api');

var app = module.exports = express();

// Configuration
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.static(__dirname + '/public'));
    app.use(app.router);
});

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
    app.use(express.errorHandler());
});

// Routes
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.get('/api/name', api.name);

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

// Start server
app.listen(3000, function(){
    console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

routes.js 文件(在 routes 目录中):

/*
 * GET home page.
 */

//get correct directory path
var filePath = __dirname.replace('routes', 'views/')

exports.index = function(req, res) {
    res.sendfile(filePath + 'index.html');
};

exports.partials = function (req, res) {
    var name = req.params.name;
    res.sendfile(filePath + 'partials/' + name + '.html');
};

似乎每个资源请求都返回索引的内容(包括图像文件)。任何想法或建议将不胜感激。

【问题讨论】:

    标签: javascript html css node.js angularjs


    【解决方案1】:

    这是你的问题:

    // redirect all others to the index (HTML5 history)
    app.get('*', routes.index);
    

    您想将它移到其他 app.get() 之前。基本上你已经告诉服务器在设置了一堆其他路由之后用index.html 响应每个请求。

    【讨论】:

    • 嘿,Jason,将这条笼统的行移到“get”的顶部似乎没有任何效果 - 索引文件仍在返回。完全取消这条线会导致 404 秒而不是 200 秒。这是否意味着我需要专门为 js/cs 文件设置路由?
    • 这绝对意味着您的文件不在正确的位置...不过,您不必为每个文件设置路线。您的公共目录中是否有公共目录,否则 index.html 中的路径中的公共是多余的?
    • 非常感谢 Jason 的帮助 - 问题在于将文件放在正确的位置(公共目录中没有公共目录)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2014-07-10
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多