Nadeem Ahmad
Nadeem Ahmad

Reputation: 745

How to access static files in node.js

I am working on node js, where I have the following directories: C:\wamp64\www\Scrapper. In the Scrapper folder, I have:

What I did is, I have included the main.js in the index.html as:

<script src="/Controllers/main.js"></script>

Also, I have declared these two folders as static in node js server.js file which is located in the main directory i.e. /Scrapper. When I run the app, it says:

http://localhost:8080/Controllers/main.js net::ERR_ABORTED 404 (Not Found)

The way I declared the static files in server.js is :

app.use(express.static(__dirname + "/Public"));
app.use(express.static(__dirname + "/Controllers"));
app.use(body_parser.json());

I don't know what the problem is. All I want is to include the main.js file in the index.html. It's a client site script which should run within that folder.

Upvotes: 2

Views: 4021

Answers (3)

Faizan Alam
Faizan Alam

Reputation: 1

const publicStaticDirPath = path.join(__dirname, '../public');
app.use(express.static.(publicStaticDirPath));

Upvotes: 0

WasiF
WasiF

Reputation: 28847

For example you have declared a static folder like

app.use(express.static(`${__dirname}/assets`))

and inside assets, you have images folder

enter image description here

then you can access the files i.e.

localhost:8080/images/koala-1550238924102.jpg

and in your case you need to do this

localhost:8080/main.js

Upvotes: 2

Halil SAFAK
Halil SAFAK

Reputation: 377

You can look in detail here.

app.use(express.static(__dirname + "/Public"));
app.use('controllers', express.static(__dirname + "/Controllers"));

Access files;

http://localhost:<port>/index.html
http://localhost:<port>/controllers/main.js

Upvotes: 1

Related Questions