Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I give direct access to my files on Hapi (Node.js) server?

Case: I want to keep *.js files for users of my website on the Hapi (Node.js) server, so they can include them CDN-like (i.e: jQuery, font-awesome).
Question: What is the proper way to do so on Hapi (Node.js) server?

What I already tried was just to link them:

<script src="https://mywebsite.com/myscripts/myjsfile.js"></script>

Or to declare route, using Inert plugin basing on Future Studio Tutorial and Hapi Documentation:

server.route({
  method: "GET",
  path: '/myscripts/{path}',
  handler: {
    directory: {
      path: '/myscripts/',
    }
  }
}

And then link them in html script tags (like above). What I've got was:

{"statusCode":403,"error":"Forbidden"}

I test it on Heroku and all the plugins I use are:

  • Hapi
  • Path
  • Joi
  • Inert
  • Handlebars
  • MongoDB
  • Vision
  • AuthCookie
  • Bell
  • Bcrypt
like image 700
wscourge Avatar asked Jan 28 '26 13:01

wscourge


1 Answers

Solution was pretty straightforward:

  1. Allow cross origin requests,
  2. Set auth to false,
  3. set handler()'s directory()'s listing to true

Route, which allows every website to access static files from www.example.com/myscripts/whatever.js

server.route({
  method: "GET",
  path: '/myscripts/{path}',
  config: {
    auth: false,
    cors: { origin: ['*'] },
    handler: {
      directory: {
        path: 'myscripts',
        listing: true
      }
    }
  }
}
like image 116
wscourge Avatar answered Jan 30 '26 05:01

wscourge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!