Nodegeek
Nodegeek

Reputation: 280

nodejs sendfile html page

I have this code that allows me to open a HTML page from specific folder, if I use server.js to open that HTMLpage so the page it is generating with all the css and jquery files but if I try to move the get statement to the routes folder then the page is generated but without any css and jquery files and I don't know why !

what I did in the server.js for the generation of the HTML page is below which is working perfectly :

const folderPath = __dirname + '/public/AppTemplate/src'
app.use(express.static(folderPath))
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname + '/public/AppTemplate/src/index.html'));
});

but what I'm trying now is to get the html page from routes.js :

step 1 : I implemented this statement in server.js

app.use('/users', require('./backend/routes/profile.routes.js'));

step2 :I tried this statement in routes.js with simple modification :D :

router.get('/profile', function (req, res) {
  const dirname = __dirname;
  console.log(dirname)
  const newpath = dirname.length - 14;
  const newP = dirname.substring(newpath, dirname.lastIndexOf("/"));
  console.log(newP);
res.sendFile(path.join(newP+ '/public/AppTemplate/src/02-ProfilePage.html'));
});

the step 2 is working but I couldn't get all the associated files (jquery css ...) which are located in

/public/AppTemplate/src

the image of the output is below : enter image description here

hope I mentioned everything, Best Regards,

Upvotes: 0

Views: 78

Answers (1)

Algo7
Algo7

Reputation: 2166

It's because of the content in the 02-ProfilePage.html has an incorrect path.

Check the path in the script tags. If there is a slash it means that it's already in the /public/AppTemplate/src which you specified.

For example, /js/file.js will actually point to /public/AppTemplate/src/js/file.js

Perhaps try adding a / in front of your path in the script tag.

Example:

/css/x/y/z/ instead of css/x/y/z

You will have to append a / to all the routes in your script/link tag to be able to successfully load the local resources.

You can use the find and replace functionality in your code editor or IDE to speed up the process if possible.

Upvotes: 1

Related Questions