Serve html file in nodejs server

强颜欢笑 提交于 2019-12-04 22:46: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.

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.

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

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

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. Just saw your EDIT. With your EDIT you are closing in on it. Change the reference in your HTML file of your script include.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!