In this video, Emmanuel Henri demonstrates how to serve static files on the Node Express server for any front end to access.
- [Instructor] When in Express Base Server, it is possible to serve static files such as images, or any other files you would like to have available from your back end. So let's go ahead and make this happen. So first of all, go inside of the Exercise Files, and the resources, and then copy the two files. So football and the sky. Then go inside of crm. And inside of the directory here just create a public folder.
So basically the way it works, Express will load anything that's in the public server so whatever files you'll put in there, you'll be able to access it. So for example in a browser. So let's go ahead and paste the two images that we have in here. But right now, it won't work if you try it. So let's go ahead and go inside of our browser. Let's make sure first that our server is running. So, yes it is. And then go inside of our browser, so let's go inside of Chrome.
And do localhost/ and try to load the sky.jpeg. And if I enter, right now it says Cannot GET /sky.jpeg. So that's normal because we need to enter just a little bit of code to make that work. So let's go inside of our code and go, and you can close the Routes and the Controllers, we're done with these. We just need to go inside of the index file, like so. And you can put this anywhere in here.
I usually put it right above the app.get and all the calls that we have in here. So let me do an app use and what I'm going to first is make sure, again, I put some notes for you so this is for serving static files. And what I'm going to do is do an app.use and use express and simply state where the public files are going to be.
So this is basically the name of the folder that holds the static files. And that's it. That's all you need to do in order to export your static files from that folder. If it was in a different folder, so for example if you had it in an images folder, you could do something like that, images. And make sure that those images are inside the public/images folder. But in this case, it's just the public. So save that.
No error. Let's go on Chrome and then reload that specific image. And now we see the beautiful sky. Let's go and do the football guy. And we got the beautiful football guy that we have in our public folders. So now, any files that are in the declare static folder will be available to any front end that needs it. So what you could do, is basically call that API and call that image from any front end app and you would have access to it.
- Setting up a project and a server
- Setting up a database and schema
- Creating POST, GET, PUT, and DELETE endpoints
- Serving files