Loading basic HTML in Node.js

后端 未结 20 1382
暗喜
暗喜 2020-11-28 17:34

I\'m trying to find out how to load and render a basic HTML file so I don\'t have to write code like:

response.write(\'...

blahblahblah

...\
20条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 18:19

    The easy way to do is, put all your files including index.html or something with all resources such as CSS, JS etc. in a folder public or you can name it whatever you want and now you can use express js and just tell app to use the _dirname as :

    In your server.js using express add these

    var express = require('express');
    var app = express();
    app.use(express.static(__dirname + '/public'));
    

    and if you want to have seprate directory add new dir under public directory and use that path "/public/YourDirName"

    SO what we are doing here exactly? we are creating express instance named app and we are giving the adress if the public directory to access all the resources. Hope this helps !

提交回复
热议问题