Node.js is a runtime environment that allows Javascript files to run outside of browser runtime; Express.js is a server-side framework built to work with Node.js
CRUD means the api allows clients to create, read, update and delete information.
Require the express module and invoke an instance.
app.listen(PORT, callback) can start a server. The first parameter is the port number argument tells the server where to listen; the callback function is executed when the server is listening and ready for response.
route is a section of Express code that is associated with an HTTP verb, a url path, and a function that is called to handle that pattern.
Express searches through the routes and responses with the first route matches the request url.
path is part of the requested url after the hostname and port.
HTTP verb(GET,PUT,UPDATE,DElETE)
app.get() is used to match the route with GET request. The first parameter is the route path(string), the second parameter is the callback function to handle the request and send a response. When a requested url arrives, req.params object will store the information from the requested url path. (query string is not necessary)
app.get('/monsters/:name', (req, res, next) => {
res.send(...); // or res.json() to send json format response
});
//request url : 'monsters/rx' req.params = {name: 'rx'}
app.put() is used to update existing data from the database. It needs data from query string.
app.post() is used to create a new resources. It needs data from query string.
app.delete() is used to delete a resource. (query string is not necessary)
req.params and req.query
route parameter is in route path and begins with ':' it. req.params stores route parameters in an object. It is like a unique identifier for the database, so the server can send the requested resource.
query string is the part of url after '?'. Express parse the information into req.query object. The value of the key is a string. It stores information the client send to the server.
Router
using router can make code cleaner. It adds the router path to the path in app.use()
Eg:
Top comments (0)