Reputation: 55
I am trying to server static files with express and them dont work, i think its express problem or something but i dont realize why it dont works. my folders look like this:
app.js public --css --js --images
and the code i trying to run like this:
app.use(express.static(path.join(__dirname,'public')));
if i do console.log of the path
console.log(path.join(__dirname, 'public'))
i get the next path C:\Users\J\Desktop\node.js\social-media-cars\public
and if i look at the path with the windows file explorer i see that the path is correct and i see the content inside, so i dont think its path fault
i also tryed :
app.use(express.static(path.join(__dirname,'public')));
app.use('/static',express.static(path.join(__dirname, '/public')));
and dont works, always the same things:
im desesparate with this, idk why this dont works.
code where i use it looks like this:
// Import the express module
const path = require('path');
const express = require("express");
// Instantiate an Express application
const app = express();
const dotenv = require("dotenv").config();
const ActionsRouter = require('./routers/actions-router');
const UserRouter = require('./routers/user-router');
const cookieparser = require('cookie-parser');
// app.use('/static',express.static(path.join(__dirname, '/public')));
//set static files that are rendered after
app.use(express.static(path.join(__dirname,'public')));
//read the cookies from response
app.use(cookieparser(path.join(__dirname, '/public')));
console.log(path.join(__dirname, 'public'))
//create the req.body
app.use(express.json());
//user
app.use("/api",UserRouter);
app.use("/useractions",ActionsRouter);
module.exports = app;
const server = app.listen(port,()=>{
console.log(`listening on port ${port}`)});
get the static files with every response i get
Upvotes: 0
Views: 993
Reputation: 55
okey i found it, i was so lost because when i try to see the files that i got in each response on the browser, i was not getting any file, but only when i linked css and html it downloaded the static file, idk why this works like this, i supposed every of /public file was atached to the response you use it or not
<link rel="stylesheet" type="text/css" href="/css/styles.css">
anyway if there is a way to get the file you request or not i would like to know
Upvotes: 1
Reputation: 1039
index.js
or app.js
above you set view engine app.use(express.static(path.join(__dirname, "public")));
|__public/
|__ css/
|__ css files...
|__ js/
|__ js files...
3. Import this way
Now you set the path to the public directory you have to give the path public folder when you import
<link rel="stylesheet" href="/css/main.css" />
In the same way, you can import your JS files
Upvotes: 1