简体   繁体   English

在Node.js服务器中提供HTML文件

[英]Serve html file in nodejs server

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. 在尝试将我的代码分为路由,控制器等之前,我一直做得很好。现在尝试加载html文件时出现错误。 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' 当我转到链接http:// localhost:3000 /时 ,出现此错误错误:ENOENT:没有这样的文件或目录,stat'/views/index.html'

This is my routes.js code 这是我的routes.js代码

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 这是我的userController.js文件

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 这是我的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. 这是我的文件夹结构。 这是文件夹结构

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 编辑:这就是我将脚本链接到html文件的方式

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

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 / ). /开头的路径是绝对路径 ,这意味着它基于根目录进行解析(在Windows中,类似于C:\\ ,在Linux中为/ )。

You should be using the path module to get paths to files relative to the module's directory like so: 您应该使用path模块来获取相对于模块目录的文件路径,如下所示:

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. __dirname是一个特殊的模块作用域变量,提供了当前模块包含目录的路径。

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

尝试在userController.js文件中添加另一个“ ..”,只有一个..会将您置于api目录。

Include the 'path' module and change 包括“路径”模块并进行更改

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

to

res.sendFile(path.resolve(`${__dirname}/views/index.html`))

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. 您正在使用res.send发送html文件,但是脚本不在静态可用文件可以访问的目录中。 Just saw your EDIT. 刚看到您的编辑。 With your EDIT you are closing in on it. 通过EDIT,您即将结束。 Change the reference in your HTML file of your script include. 在HTML文件中更改脚本包含的引用。

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. 在您的情况下,您可以使用server.js文件(在根目录中)启动服务器,也可以从中启动它。因此,您给静态函数的路径是相对于此位置的。

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

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