I have changed my Express.js project to use bower to install components. All components are installed under /components (/components/jquery/jquery.js ...etc).
I have create my own router as well which looks like this:
app.get('/', routes.index); // main page
app.get('/p/:name', routes.p); //redirect routes
app.get('/api/contacts', api.contacts); //look at all
app.get('/api/contact/:id', api.contact); //look at one
app.post('/api/contact', api.add); //add contact
app.put('/api/contact/:id', api.edit); //edit&update contact
app.delete('/api/contact/:id', api.delete); //delete contact
There are no routes for /components therefore http://my.project/components/jquery/jquery.js
comes back with a Cannot GET /components/jquery/jquyery.js
Can someone please let me know what's the best way to add routing for all the components under /components?
A route method is derived from one of the HTTP methods, and is attached to an instance of the express class. The following code is an example of routes that are defined for the GET and the POST methods to the root of the app. Express supports methods that correspond to all HTTP request methods: get , post , and so on.
Router() Function. The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.
Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.
Routing with Express in Node: Express. js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function, which is called when a request is received.
You probably want to use the static middleware to do this. I am not familiar with bower but if all your components are install in /components
then you can do the following:
app.use(express.static(__dirname + '/components'));
This means if you have /components/jquery/jquery.js
you can include it with
<script src='/jquery/jquery.js'></script>
If you rather prefix it with /components
you can do:
app.use('/components', express.static(__dirname + '/components'));
That way you can request the scripts with:
<script src='/components/jquery/jquery.js'></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With