快速静态不提供文件

时间:2016-05-29 03:02:32

标签: javascript node.js express

我知道其他人已经就此话题提出了问题,但我无法通过阅读答案来弄清楚我的问题。

我希望我的Node.js应用程序能够提供我的文件,看起来好像该页面正在向正确的路径请求css文件,但它仍然无效。

HTML正在使用链接标记<link rel="stylesheet" href="../public/css/register.css">

http://localhost:3000/public/css/register.css请求css文件

app.js

//Load modules
var express = require('express');
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var app = express();
var router = express.Router();
var fs = require('module');
var path = require('path');

//Load body-parser and other middleware
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname + '/public')));

//Load routes
var users = require('./routes/users');

//Routes
app.use('/users', users);


//Run Server
app.listen(3000, function(){
  console.log("Listening on Port 3000");
});

users.js

//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("mongodb://MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')

//Express Setup
var express = require('express');
var router = express.Router();
var app = express();

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


//Define Schema
var userSchema = new Schema({
  name: String,
  email: String,
  password: String
});
var User = mongoose.model('User', userSchema);

//Routes
router.get('/register', function(req, res){
  res.sendFile(appDir + "/views/register.html");
})

router.post('/register', function(req, res) {
  console.log('Post Request')
  var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password
  })
  newUser.save();
  res.redirect('/users/register');
})

//Exports
module.exports = router;

当前文件结构

/MAIN
    /public
        /css
            register.css
    /routes
        users.js
    /views
        register.html
    package.json

2 个答案:

答案 0 :(得分:1)

愚蠢的问题,我必须将来源设为<link rel="stylesheet" href="/css/register.css">而不是<link rel="stylesheet" href="../public/css/register.css">

答案 1 :(得分:0)

您指向css文件的链接应为/public/....而非../public/..