That Guy
That Guy

Reputation: 195

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.

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">

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;

Current File Structure

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

Upvotes: 1

Views: 752

Answers (2)

That Guy
That Guy

Reputation: 195

Dumb issue, I had to put the source as <link rel="stylesheet" href="/css/register.css"> instead of <link rel="stylesheet" href="../public/css/register.css">

Upvotes: 1

theatlasroom
theatlasroom

Reputation: 1184

Your link to the css file should be /public/.... not ../public/..

Upvotes: 0

Related Questions