| Start | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic routing First create an express app: Then you can define routes like this: That structure works for all HTTP methods, and expects a path as the first argument, and a handler for that path, which receives the request and response objects. So, for the basic HTTP methods, these are the routes You can check the complete list of supported verbs here (opens new window). If you want to define the same behavior for a route and all HTTP methods, you can use: or or You can chain your route definitions for a single path You can also add functions to any HTTP method. They will run before the final callback and take the parameters (req, res, next) as arguments. Your final callbacks can be stored in an external file to avoid putting too much code in one file: And then in the file containing your routes: This will make your code much cleaner. |
||||||||||||||
| Getting Started You will first need to create a directory, access it in your shell and install Express using npm (opens new window) by running Create a file and name it To run your script use the following command in your shell: Your application will accept connections on localhost port 8080. If the hostname argument to Once your script is running, you can test it in a shell to confirm that you get the expected response, "pong", from the server: You can also open a web browser, navigate to the url http://localhost:8080/ping (opens new window) to view the output |
||||||||||||||
| Modular express application To make express web application modular use router factories: Module: Application: This will make your application modular, customisable and your code reusable. When accessing More complicated exampleExample with services that shows middleware factory advantages. Module: Application: When accessing |
||||||||||||||
Using a Template Engine Using a Template EngineThe following code will setup Jade as template engine. (Note: Jade has been renamed to Similarly, other Template Engines could be used too such as EJS Template ExampleWith EJS (like other express templates), you can run server code and access your server variables from you HTML. As you can see in the example every time you switch between server side code and HTML you need to close the current EJS tag and open a new one later, here we wanted to create Here the message variable passed from your server side will be the default value of your input, please be noticed that if you didn't pass message variable from your server side, EJS will throw an exception. You can pass parameters using |
||||||||||||||
JSON API with ExpressJS On |
||||||||||||||
| Serving static files When building a webserver with Express it's often required to serve a combination of dynamic content and static files. For example, you may have index.html and script.js which are static files kept in the file system. It is common to use folder named 'public' to have static files. In this case the folder structure may look like: This is how to configure Express to serve static files: Note: once the folder is configured, index.html, script.js and all the files in the "public" folder will be available in at the root path (you must not specify will make the resources available under the Multiple foldersIt is possible to define multiple folders at the same time: When serving the resources Express will examine the folder in definition order. In case of files with the same name, the one in the first matching folder will be served. |
||||||||||||||
| Getting info from the request To get info from the requesting url (notice that You can also get headers of the request, like this To simplify getting other info you can use middlewares. For example, to get the body info of the request, you can use the body-parser (opens new window) middleware, which will transform raw request body into usable format. Now suppose a request like this You can access the posted name like this In a similar way, you can access cookies from the request, you also need a middleware like cookie-parser (opens new window) |
||||||||||||||
| Error Handling Basic Error Handling By default, Express will look for an 'error' view in the views/error.pug Advanced Error Handling Define your error-handling middleware functions at the very end of the middleware function stack. These have four arguments instead of three app.js You can define several error-handling middleware functions, just as you would with regular middleware functions. |
||||||||||||||
| Adding Middleware Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can execute any code, make changes to Very common example of middleware is before any routers or routing functions. |
||||||||||||||
| Hook: How to execute code before any req and after any res
An example of this is the logger (opens new window) middleware, which will append to the log after the response by default. Just make sure this "middleware" is used before Original post is here (opens new window) |
||||||||||||||
| Error handling in Express In Express, you can define unified error handler for handling errors occurred in application. Define then handler at the end of all routes and logic code. Example |
||||||||||||||
| Named routes in Django-style One big problem is that valuable named routes is not supported by Express out of the box. Solution is to install supported third-party package, for example express-reverse (opens new window): Plug it in your project: Then use it like: The downside of this approach is that you cant use And use it like: You can figure it out from now on, how define functions to merge it with specified custom namespaces and point at appropriate controllers. |
||||||||||||||
| Setting cookies with cookie-parser The following is an example for setting and reading cookies using the cookie-parser (opens new window) module: |
||||||||||||||
| Custom middleware in Express In Express, you can define middlewares that can be used for checking requests or setting some headers in response. Example The following code adds |
||||||||||||||
| Hello World Here we create a basic hello world server using Express. Routes:
And for rest will give "404" , i.e. page not found. Note: We have put 404 route as the last route as Express stacks routes in order and processes them for each request sequentially. |
||||||||||||||
| Using middleware and the next callback Express passes a Multiple matching routes Requests to Error handler Error handlers are middleware with the signature Middleware Each of the functions above is actually a middleware function that is run whenever a request matches the route defined, but any number of middleware functions can be defined on a single route. This allows middleware to be defined in separate files and common logic to be reused across multiple routes. In this example, each middleware function would be either in it's own file or in a variable elsewhere in the file so that it could be reused in other routes. |
||||||||||||||
| Error handling Basic docs can be found here (opens new window) Appendix A Appendix B |
||||||||||||||
| Handling POST Requests Just like you handle get requests in Express with app.get method, you can use app.post method to handle post requests. But before you can handle POST requests, you will need to use the
Syntax
Parameters
|
Read Article
https://develop.horje.com/learn/1434/reference