【发布时间】:2014-08-08 03:29:48
【问题描述】:
我是 Express 的新手,也是 nodejs 的半新手,我正在尝试运行一个简单的应用程序/网络服务器作为概念证明。我被困了好几个小时,因为我的服务器将每个文件都作为 index.html (包含 index.html 的内容)。
在我的 index.html 中,我正在调用 JS 文件和 CSS 文件,它们都回来了,但控制台中有 200,但它们都回来了 index.html 内容,而不是其中包含的实际内容.我相信问题出在下面的 server.js 文件中:
// server.js
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
var path = require('path');
// configuration ===========================================
// config files
var db = require('../config/db');
var port = process.env.PORT || 9999; // set our port
//mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('../../app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:9999
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
// app/routes.js
module.exports = function(app) {
// server routes ===========================================================
// handle things like api calls
// authentication routes
// sample api route
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
// route to handle creating (app.post)
// route to handle delete (app.delete)
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('/Users/...../app/public/index.html'); // load our public/index.html file
//res.sendfile(path, {'root': '../'});
});
};
我一直在逐字阅读本教程:http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application,但没有取得太大成功。
【问题讨论】:
-
你的 server.js 在你的 routes.js 之后看起来很好,你的目录结构也很有用。
-
感谢您的浏览,我已经添加了我的 routes.js 和我的目录。结构
-
澄清问题是该应用程序根本无法运行。没有加载任何 javascript 或 css,因此没有 angularjs 也没有引导程序。所有 JS 和 CSS 都作为 index.html 文件返回到浏览器。
标签: javascript node.js angularjs express mean-stack