Home > Software engineering >  How can I access the files used in a HTML file on a website with Node.JS
How can I access the files used in a HTML file on a website with Node.JS

Time:10-18

I am having a problem with Node.JS.

I'm trying to upload a HTML file with Node.JS (the HTML file has links to JS, JSON and CSS files) but when I turn on the server and look at the page, only what was in the HTML is written, which means there is no CSS and no JS which were working properly before I implemented the server.

Can anyone help me?

Here's the Node.JS code:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.static('project-folder'));

app.get('/', function(req, res){
    res.sendFile('website.html', { root: __dirname });
});

app.listen(port, function(){
    console.log("server is up");
});

CodePudding user response:

If your folder structure looks like this:

project-folder
  |-website
  |  |-style.css
  |  |-script.js
  |-website.html
  |-server.js

then the code should look like this:

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

app.use(express.static(path.join(__dirname, 'website')));


app.get('/', function(req, res){
    res.sendFile('website.html', { root: __dirname });
});

app.listen(port, function(){
    console.log("server is up");
});

if it's like this:

project-folder
  |-website
  |  |-style.css
  |  |-script.js
  |  |-website.html
  |-server.js

then the code should look like this:

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

app.use(express.static(path.join(__dirname, 'website')));


app.get('/', function(req, res){
    res.sendFile('website.html', { root: path.join(__dirname, 'website') });
});

app.listen(port, function(){
    console.log("server is up");
});

Mind the path module that is required at the top

  • Related