1

I'm having issues trying to serve static files with expressJS. I want to serve files from a folder, using virtual route.

My app architecture looks like this

├── app
|   ├── assets
|       └── data
|           └── img
|               └── cards
|                   └── * (un bunch of image files)
|   └── index.js
|   └── server.js
├── node_modules
├── package.json
├── package-lock.json

My index.js

const express = require('express');
const path = require('path');
const app = express();


//Serving images
app.use('resources/cards', express.static(path.join('assets/data/img/cards')));
app.get('/', function (req, res) {
   res.send('Hello World');
});

module.exports = app;

My server.js

const app = require('./index');
const config = require('./config');
//Mysql connection
const mysql = require('mysql');



app.listen(config.express.port, function() {
    console.log(`Running on ${config.express.ip}:${config.express.port}`);
});


const connection = mysql.createConnection({
    host: config.mysql.host,
    user: config.mysql.username,
    password: config.mysql.password,
    port: config.mysql.port,
    database: config.mysql.database,
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
    if (err) throw err;
    console.log(`The solution is ${rows[0].solution}`);
});

//connection.end();


I want to access my images through localhost:3000/resources/cards/image.png, for example, but still getting this Cannot GET /resources/cards

1 Answers1

0

Try by specifying the mount path as absolute and add __dirname to the path.join(...):

app.use('/resources/cards', express.static(path.join(__dirname, 'assets/data/img/cards')));
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
  • Still getting ```Cannot GET /resources/cards``` , I have this console error. I don't think it's helping but : ```Refused to load the image 'http://localhost:3000/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.``` – Damien Letellier Nov 12 '19 at 11:03
  • that's not related to this. The browser makes an extra request to `/favicon.ico` with each request (you can make a request to `http://localhost:3000/` and see you'll also have another request to `/favicon.ico`) – Tudor Constantin Nov 12 '19 at 11:06
  • Ok, thank you for the explaination ! I looking for answers in Express documentation but I don't see what i'm doing wrong... Could my app architecture be related to this ? – Damien Letellier Nov 12 '19 at 11:14
  • 1
    It worked ! I didn't see but I typed ```path.join(__dirname + '/assets/data/img/cards')``` instead of ```path.join(__dirname, 'assets/data/img/cards')``` Thank you a lot ! – Damien Letellier Nov 12 '19 at 11:18