Home > Enterprise >  Node.js express can not get the css and js file
Node.js express can not get the css and js file

Time:05-25

Here is my main.ts file I can not get my css and js file enter image description here

import express from 'express';
import {Request,Response} from 'express';
import expressSession from 'express-session';
import path from 'path';

const app = express();


// set session 
app.use(expressSession({
    secret: 'Tecky Academy teaches typescript',
    resave:true,
    saveUninitialized:true
}));

// teach the server to go to the main page//
app.get("/", (req: Request, res: Response) => {
  res.sendFile(path.resolve(__dirname, "../frontend/public/index.html"));
});



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

const PORT = 8080;

app.listen(PORT, () => {
    console.log(`Listening at http://localhost:${PORT}/`);
});

And here is my file structure enter image description here

CodePudding user response:

seems from the screenshot that your public folder is empty. you seem to have the index.html and other files in your frontend folder and not in the public folder. your index.js and your index.html are on the same level. so your path does not resolve correctly if you resolve it from the index.js file

from which file are you resolving the path? from index.js or main.ts?

CodePudding user response:

First things first, you shouldn't post the app secret in a public forum. Second, can you post your index.html file? Chances are it incorrectly loads the JS and CSS files. Third, you can import default and class exports from a package in one line. Change

import express from 'express';
import {Request,Response} from 'express';

to

import express, { Request, Response } from 'express';
  • Related