Public Directory - Node.js

Asked

Viewed 365 times

1

Public Directory Node.js

I’m having problems releasing a public directory on Node.js. I need everything in the directory public is accessible via direct URL.

I’ve tried to use app.use(express.static('public')); however unsuccessfully.

I’m using these dependencies:

"dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "mssql": "^4.1.0",
    "multer": "^1.4.1"
  }

The file should be accessed by some URL similar to:

Or Node does not have this support?

EDIT 1: Adding Images.

Index.js:

Código fonte Node.js

Directory: Diretório

Attempt 1 Tentativa1

Attempt 2 Tentativa2

Folder Structure:

Pastas

Route:

Rota

1 answer

1


Maybe the Node is not looking in the correct directory when you create the endpoint. Change to the following:

const path = require('path');

// ...

application.use('/public', express.static(path.join(__dirname, 'public')));

And so access:

/public/uploads/nfd/1550581279905_boleto.pdf

Or:

const path = require('path');

// ...

application.use(express.static(path.join(__dirname, 'public')));

And so access:

/public/uploads/nfd/1550581279905_boleto.pdf

Or else:

const path = require('path');

// ...

application.use(express.static('/consultaavancada', path.join(__dirname, 'public')));

And so access:

/consultaavancada/uploads/nfd/1550581279905_boleto.pdf
  • thanks for the help. But I tested both ways and it didn’t work. From what I saw on the internet this would work in case I want to import js, css or img files to the page in question. But what I really want is that I can access this PDF directly through the link, outside the site.

  • I edited the question to add images, see if it helps better so... Anything I put more information if you need.

  • I added the folder structure and routes

  • @Pedrodaher out that your URL seems to be wrong. Make the call without the consultaavancada: http://localhost:3020/public/uploads/nfd/1550581279905_boleto.pdf

  • I made the call without the consultaavancada and it wasn’t either, but I think I should keep it, because on the route it is configured.

  • @Pedrodaher tried both ways without the consultaavancada?

  • I tested yes, I did a test added the consultaavancada in the code you posted up there, getting app.use('/consultaavancada/public', express.static(path.join(__dirname, 'public'))); and it worked. You saved me man!! Thank you so much.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.