Advertisement
Guest User

Untitled

a guest
Oct 20th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express')
  2. const app = express()
  3.  
  4. let id = 0
  5. let products = [
  6.     {id:id++,
  7.      name: 'car',
  8.      price: 50},
  9.  
  10.      {id:id++,
  11.      name:'phone',
  12.      price: 5},
  13. ]
  14.  
  15. app.get('/', (req,res)=>{
  16.     res.send('Hellsadadada o')
  17. })
  18.  
  19. app.get('/users/:userId(\\d)', (req,res)=>{
  20.     const userId = req.params.userId
  21.     res.send(`user id - ${userId}`)
  22. })
  23.  
  24.  
  25.  
  26. app.get('/products', (req, res)=>{
  27.     res.send(
  28.      products.map( product => {
  29.          return ` <h2 id= "product-${product.id}"
  30.          data-id="${product.id}"    
  31.          onclick="window.location.replace('http://localhost:4000/products/${product.id}')">
  32.          ${product.name}
  33.          </h2>`
  34.                        
  35.         }).join(' ')
  36.     )
  37. })
  38.  
  39. app.get('/products/:productId', (req,res)=>{
  40.     const id = req.params.productId;
  41.     const Product = products.find( prod => prod.id == id);
  42.  
  43.     let response = " <a href='http://localhost:4000/products/'>Go Back </a> <h1>Product not found </h1> "
  44.     if(Product){
  45.         response = `
  46.         <a href='http://localhost:4000/products/'>Go Back </a>
  47.         <h1>${Product.name}</h1>
  48.         <hr>
  49.         <h2>Price ${Product.price}, id - ${Product.id} </h2>
  50.         `
  51.    
  52.     }
  53.     res.send(response);
  54. })
  55.  
  56. app.listen(4000);
  57.  
  58.  
  59. app.post('/products/:id/:name/:price', (req,res)=>{
  60.     let product = {
  61.         id: req.params.id,
  62.         name: req.params.name,
  63.         price: req.params.price
  64.     }
  65.  
  66.     products.push(product);
  67.     res.json( {message: 'Product created', product});
  68. })
  69.  
  70. app.delete('/products/:id', (req,res)=>{
  71.     const id = products.findIndex( p => p.id == req.params.id);
  72.     const product = products[id];
  73.     products.splice(id,1);
  74.     res.json( {message : 'Product deleted', product})
  75. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement