Serve html file in nodejs server

2019-04-17 11:49发布

I've been doing fine until I try to separate my code into routes, controllers and etc. Now I'm getting an error when I try to load the html file. When I go to the link http://localhost:3000/ I'm getting this error Error: ENOENT: no such file or directory, stat '/views/index.html'

This is my routes.js code

module.exports = function (app) {
    var userController = require('../controllers/userController');

    // app.use(require('express').static('../app/views/index.html'));

    app.get('/', userController.renderHomePage);

    app.post('/find', userController.getUser);
    app.get('/get', userController.getUsers);
    app.post('/add', userController.addUser);
}

And here's my userController.js file

var mongoose = require('mongoose');
var User = require('../models/user');

var express = require('express');

var app = express();
app.use(express.static('../app'));

exports.renderHomePage = function (req, res) {
    res.sendFile('/views/index.html');
}

exports.addUser = function(req,res){
    console.log(req.body);

    var newUser = new User({
        name : req.body.name,
        username : req.body.username,
        password : req.body.password
    });

    newUser.save(function(err){
        if(err){
            console.log(err);
        }
        else{
            console.log("User Saved successfully");
        }
    });

    res.send(req.body);
};

exports.getUsers = function (req, res) {
    // body...
    User.find({}, function(error, users){
        if(error){
            console.log(error);
        }
        else{
            res.send(users);
        }
    })
};

exports.getUser = function (req, res) {
    // body...
    console.log(req.body);
    var data = req.body.username;

    User.find({username : data}, function(err, user){
        if(err){
            throw err
        }
        else{
            console.log(user);
            res.send(user);
        }
    } );
};

Here's my server.js

var express = require('express');
// var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var PORT = process.env.PORT || 3000;

var app = express();

var routes = require('./api/routes/routes');
routes(app);

var database = require('./config/database');

app.use(bodyParser.json());

app.listen(PORT, function(){
    console.log("Server is running on port "+PORT);
})

And here's my folder structure. Here's the folder structure

Server starting without an error. And I thought I've given the paths correctly. But I'm getting the error. Can anyone help me with this ? Thanks.

EDIT : This is how I've linked my script to the html file

<script src="/script/app.js"></script>

5条回答
淡お忘
2楼-- · 2019-04-17 11:50

A path starting with / is an absolute path, meaning it resolves based on the root directory (on Windows, something like C:\, on linux it's just /).

You should be using the path module to get paths to files relative to the module's directory like so:

var path = require('path');
var filePath = path.join(__dirname, 'relative/path/to/file');

__dirname is a special module-scoped variable that provides the path to the current module's containing directory.

查看更多
SAY GOODBYE
3楼-- · 2019-04-17 11:52

Include the 'path' module and change

res.sendFile('/views/index.html');

to

res.sendFile(path.resolve(`${__dirname}/views/index.html`))
查看更多
疯言疯语
4楼-- · 2019-04-17 11:57

I ran into this problem. You are sending the html file with res.send, but your scripts are not in a directory that can be reached by your statically available files. Just saw your EDIT. With your EDIT you are closing in on it. Change the reference in your HTML file of your script include.

查看更多
叛逆
5楼-- · 2019-04-17 12:05
app.use(express.static('../../app'))

Try adding another '..' in your userController.js file, just one .. will put you at the api directory.

查看更多
forever°为你锁心
6楼-- · 2019-04-17 12:08

It's been two months, did you solve the problem ?

If not did you try that code :

app.use(express.static('app'));

The path you give to the static function is relative to the directory where you run your node process.

In your case, you start your server with/from the server.js file (at the root directory), so the path you give to the static function is relative to this location.

查看更多
登录 后发表回答