Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const db = {
- users: [
- { name: 'John' },
- { name: 'Jane' }
- ]
- };
- function users(req, res, next) { // The users component will throw a notFoundError when a user doesn’t exist.
- 'use strict';
- let match = req.url.match(/^\/user\/(.+)/); // match the req.url using regexp
- console.log(db.users); // [ { name: 'tobi' }, { name: 'loki' }, { name: 'jane' } ]
- console.log(db.users[match[1]]); // Why db.users[match[1]] always respond as 'undefined' ?
- if (match) { // check if the user index exists by using match[1]
- //let user = db.users[match[1]]; // which is the first capture group
- if (user) { // if the user exists, it's serialized as JSON
- req.setHeader('Content-Type', 'application/json');
- res.end(JSON.stringify(user));
- } else { // otherwise an error is passed to the next() function
- let err = new Error('User not found'); // with its notFound property set to true
- err.notFound = true;
- next(err);
- }
- } else {
- next();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement