1

I have the following basic folder structure:

main_folder
├──web
│  ├──files_located_here
│  │  ├──dog.jpg
│  │  ├──cat.jpg
│  │  ├──bat.jpg
│  │  └──rat.jpg    
│  ├──app.js
│  ├──package.json
│  └──package-lock.json

inside app.js I have this:

const CORS = require('cors');
const EXPR = require('express');
const app    = EXPR();
const router = EXPR.Router();

app
  .use(CORS())
  .use('/', router)
  .use(EXPR.urlencoded({ extended: false }));

router.get('/', (req, res) => {
  req.accepts(['json', 'text'])
  res.setHeader('content-type', 'text/html')
  res.json("sup")
});

app.listen(12, () => 
  console.log("ctrl + click => http://123.123.0.12:12/"));

This will render just fine. But if I try navigating to http://123.123.0.12:12/files_located_here/cat.jpg I get Cannot GET /files_located_here/cat.jpg.

What I don't understand is, I followed these instructions and it works as expected when windows is hosting the app. But when I use regular folder it won't navigate to the folder. I have tried EXPR.static and that didn't work. Is this a permission issue? Could it be the server has not been set up to allowing web access?

Rookie
  • 140
  • 1
  • 3
  • 13
  • 3
    I don't see any route for something other than `/` . If you tried `express.static` and it didn't work, you probably did something wrong, because `express.static` is the way to go for serving static files – derpirscher Aug 17 '22 at 05:43
  • Express does not serve ANY files by default. It only serves files that some route is configured to serve. Right now, the code you show only shows a route for `/`. If you want to serve a whole directory of static files, then properly configure the `express.static()` middleware into a route. – jfriend00 Aug 17 '22 at 05:48
  • @jfriend00 I know I’m missing settings somewhere. How does windows IIS do it? The exact same ‘app.js’ file will work if windows is the main server. – Rookie Aug 17 '22 at 12:51
  • Then, probably IIS is serving static files, not your nodejs server. The nodejs code you show does not serve any static files from anywhere. It has one route for `/` and that's it. – jfriend00 Aug 17 '22 at 15:57

1 Answers1

0

I was doing something wrong, as @derpirscher pointed out. Here's the fix:

const CORS = require('cors');
const EXPR = require('express');
const app    = EXPR();
const router = EXPR.Router();

app
  .use(CORS())
  .use('/', router)
  .use('/shortenedlink', EXPR.static('./files_located_here'))
  .use(EXPR.urlencoded({ extended: false }));

router.get('/', (req, res) => {
  req.accepts(['json', 'text'])
  res.setHeader('content-type', 'text/html')
  res.json("sup")
});

app.listen(12, () => 
  console.log("ctrl + click => http://123.123.0.12:12/"));

and now if I navigate to:

http://123.123.0.12:12/shortenedlink/dog.jpg
http://123.123.0.12:12/shortenedlink/cat.jpg
http://123.123.0.12:12/shortenedlink/bat.jpg
http://123.123.0.12:12/shortenedlink/rat.jpg

they all render properly.

Rookie
  • 140
  • 1
  • 3
  • 13