简体   繁体   English

Express Static 不提供文件

[英]Express Static not Serving Files

I know that other people have asked questions regarding this topic, but I was unable to figure out my issue from reading the answers.我知道其他人已经提出了有关此主题的问题,但我无法通过阅读答案找出我的问题。

I want my Node.js app to serve my files, and it looks as if the page is making a request for the css file to the correct path, but it is still not working.我希望我的 Node.js 应用程序为我的文件提供服务,并且看起来好像页面正在向正确的路径请求 css 文件,但它仍然无法正常工作。

The HTML is making a request to http://localhost:3000/public/css/register.css for the css file using the link tage <link rel="stylesheet" href="../public/css/register.css"> HTML 正在使用链接标签向http://localhost:3000/public/css/register.css请求 css 文件<link rel="stylesheet" href="../public/css/register.css">

app.js应用程序.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用户.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;

Current File Structure当前文件结构

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

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

您指向 css 文件的链接应该是/public/....而不是../public/..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM