title: Need help Posting external API call to a local postgres database
body: <p>I'm working on a project that successfully displays the requested API call on a card in my HTML. I want to use a button click on that card to POST the same information to my local database of Favorites, then Get that Database to display on screen when called.</p>
  <p>I've created the routes already that work in postman, just can link the external database to my local server.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//GameZ Backend Project
  
  // document.getElementById('search').addEventListener('click', singleGame)
  
  const express = require('express');
  const app = express();
  const { sequelize, Game, Favorites, Wishlist, User } = require('./models')
  
  const bodyParser = require('body-parser');
  const es6Renderer = require('express-es6-template-engine');
  const fetch = require("node-fetch");
  // const prohairesis =reqiure("prohairesis");
  // const dotenv = require("dotenv");
  
  //app.use('/', require('./routes/endpoints'));
  
  const winston = require('winston');
  const moment = require('moment');
  const pg = require('pg-promise')();
  
  const bcrypt = require('bcrypt');
  const { response } = require('express');
  
  //To convert the request to readable json format, we use bodyparser package
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: false}))
  
  app.engine('html', es6Renderer);
  app.set('views', 'templates');
  app.set('view engine', 'html');
  
  app.use(express())
  
  const logger = winston.createLogger({
      level: 'info',
      defaultMeta: { service: 'Game' },
      transports: [
          new winston.transports.File({ filename: 'error.log', level: 'error' }),
          new winston.transports.File({ filename: 'combined.log' }),
      ]
  })
  
  // Middleware is the mediary that modifies information sent between the client and server
  app.all('*', (req, res, next) =&gt; {
      logger.info({
          "Action": req.method,
          "Path": req.path,
          "Content_Type": req.header('Content-Type'),
          "Body": req.body,
          "Time": moment().format('MM/DD/YYYY, h:mm:ss a')
      })
      next()
  })
  
  app.get('/home', (req, res) =&gt; {
     
      res.render('index2', {
          locals: {
              //    name: '',
              //    games: []
              }
          });
      })
  
  
  
     
  //Get all games from gameInfo (app.get)
  app.get('/gameInfo', async (req, res) =&gt; {
      let gaming = await Game.findAll();
      
      res.send(gaming)
      console.log(gaming)
  })
      
  
  // Get a single game from the gameList (app.get)
  // function singleGame(){
  
  // let SGame = document.getElementById("singleGame").value
  // let idArray = []
  app.post('/home', async (req,res)=&gt; {
     
      const userInput = req.body.search;
      const urlEncodedSearchString = encodeURIComponent(userInput);
      
     
      let games = await fetch(`https://rawg.io/api/games?key=c1be38abe1e74ea3a7b554f19b8a9df6&amp;search=${urlEncodedSearchString}`)
      let gamesJson = await games.json()
      let allGames = gamesJson.results.slice(0,8)
        
          res.render('index3', {
          locals: {
                 games: allGames,
                 name: ''
              }
          });
          
  })    
  
  app.get('/home/2', async (req,res) =&gt; {
      
      let gameCard = {}
      //fetch using search by name
      fetch(`https://rawg.io/api/games?key=c1be38abe1e74ea3a7b554f19b8a9df6&amp;search=batman`)
      .then((response) =&gt;{
          return response.json()
      })
      .then(data =&gt; {
          console.log(data)
          
          for (let index = 0; index &lt; data.results.length; index++) {
          
          gameCard = {
             name: data.results[index].name,
             id: data.results[index].id,
              rating:data.results[index].rating,
              released: data.results[index].released,
              img: data.results[index].background_image
          }
          console.log(gameCard)
          
          }
          res.send(gameCard)
      })
      
      
  
  })
  
  app.get('/oneresult/:gameslug' , async (req, res) =&gt; {
      let faveCard = {}
      console.log(req.params.gameslug, "IM HERE")
      let games = await fetch(`https://rawg.io/api/games/${req.params.gameslug}?key=c1be38abe1e74ea3a7b554f19b8a9df6`)
      console.log(games)
      let gamesJson = await games.json()
      console.log(gamesJson)
      let allGames = gamesJson
        console.log(allGames)
          
          res.render('FavoritesWish', {
          locals: {
                 game: allGames,
                 name: ''
              }
          });   
  
    } )
      
  
  
  
  
  app.get('/gameList', async (req, res) =&gt; {
  
      
    
      let gaming = await Game.findOne ({
          where: {
             
          }
      })
      if (gaming == null) {
          res.statusCode = 400;
          res.render('Not found');
      } else {
          res.statusCode = 200;
          // res.send(gaming);
          res.send('gaming', {
              locals: {
                  gaming,
                  
              }
          });
      }
  })
  // }
  
  // Add a game to the gameList
  app.post('/gameInfo', async (req, res) =&gt; {
  
      
  
  
      let createdUser = await Game.create(
      { 
          gamename: req.body.gamename,
          gameid: req.body.gameid,
          star: req.body.star,
          review: req.body.review,
          username: req.body.username
      } 
      ) 
      res.statusCode = 200;
      res.send(createdUser);
  });
  
  
  
  
  //Get all Favorites from Info (app.get)
  // app.get('/favInfo', async (req, res) =&gt; {
  //     let favoritesgame = await Favorites.findAll();
  
  //     res.send(favoritesgame)
      
  // })
  
  // Get a single game from the favList (app.get)
  app.get('/favList/:id', async (req, res) =&gt; {
      let favoritesgame = await Favorites.findOne ({
          where: {
              id: req.params.id
          }
      })
      if (favoritesgame == null) {
          res.statusCode = 400;
          res.render('Not found');
      } else {
          res.statusCode = 200;
          // res.send(favoritesgame);
          res.render('gaming', {
              locals: {
                  favoritesgame,
                  
              }
          });
      }
  })
  
  
  // Add a game to the FavoritesList
  app.post('/favInfo', async (req, res) =&gt; {
      let createdFavorites = await Favorites.create(
      { 
          gamename: req.body.gamename,
          platform:req.body.platform,
          gameid: req.body.gameid,
          star: req.body.star,
          releasedate: req.body.releasedate,
          username: req.body.username
      } 
      ) 
      res.statusCode = 200;
      res.send(createdFavorites);
  });
  
  
  
  
  //Get all Wishlist from Info (app.get)
  app.get('/wishInfo', async (req, res) =&gt; {
      let wishlistgame = await Wishlist.findAll();
  
      res.send(wishlistgame)
      
  })
  
  // Get a single game from the WishList (app.get)
  app.get('/wishList/:id', async (req, res) =&gt; {
      let wishgame = await Wishlist.findOne ({
          where: {
              id: req.params.id
          }
      })
      if (wishgame == null) {
          res.statusCode = 400;
          res.send('Not found');
      } else {
          res.statusCode = 200;
          // res.send(wishlistgame);
          res.render('wishlistgame', {
              locals: {
                  wishgame,
                  
              }
          });
      }
  })
  
  
  // Add a game to the WishList
  app.post('/wishInfo', async (req, res) =&gt; {
      let createdwishList = await Wishlist.create(
      
      
      { 
          gamename: req.body.gamename,
          gameid: req.body.gameid,
          rating: req.body.rating,
          username: req.body.username
      } 
      ) 
      res.statusCode = 200;
      res.send(createdwishList);
  });
  
  
  
  
  // Delete a game from the gameList
  app.delete('/gameInfo/:gamename', async (req, res) =&gt; {
      let deletedGames = await Game.destroy({
          where: {
              gamename: req.params.gamename
          }
      })
      res.sendStatus(200).send(deletedGames);
  })
  
  // Delete a game from the Favorites
  app.delete('/favInfo/:gamename', async (req, res) =&gt; {
      let deletedGames = await Favorites.destroy({
          where: {
              gamename: req.params.gamename
          }
      })
      res.sendStatus(200).send(deletedGames);
  })
  
  // Delete a game from the gameList
  app.delete('/wishInfo/:gamename', async (req, res) =&gt; {
      let deletedGames = await Wishlist.destroy({
          where: {
              gamename: req.params.gamename
          }
      })
      res.sendStatus(200).send(deletedGames);
  })
  
  
  
  // Add a game to the gameList
  app.post('/favInfo', async (req, res) =&gt; {
      let createdUser = await Favorites.create(
      { 
          gamename: req.body.gamename,
          gameid: req.body.gameid,
          star: req.body.star,
          review: req.body.review,
          username: req.body.username
      } 
      ) 
      res.statusCode = 200;
      res.send(createdUser);
  });
  
  // app.post('/pushFav', async (req,res)=&gt;{
  
  
  //     gameCard = {
  //         name: data.results[index].name,
  //         id: data.results[index].id,
  //          rating:data.results[index].rating,
  //          released: data.results[index].released,
  //          img: data.results[index].background_image
  //      }
  //      console.log(gameCard)
       
  //      }
  //      res.send(gameCard)
      
  // });
  
  //Update the meta for a game
   app.patch('/gameInfo/:gamename', async (req, res) =&gt;{
  
      let gPatch = await Game.update(
          {
              gamename: req.body.gamename,
              gameid: req.body.gameid,
              star: req.body.star,
              review: req.body.review,
              username: req.body.username, 
           },    {
                    where:{
                        gamename: req.params.gamename
                    }
                } 
          
      )
      res.sendStatus(200).send(gPatch);        
   })
  
  //Update the meta for a Favorites
   app.patch('/favInfo/:gamename', async (req, res) =&gt;{
  
      let gPatch = await Favorites.update(
          {
              gamename: req.body.gamename,
              gameid: req.body.gameid,
              star: req.body.star,
              review: req.body.review,
              username: req.body.username, 
           },    {
                    where:{
                        gamename: req.params.gamename
                    }
                } 
          
      )
      res.sendStatus(200).send(gPatch);          
   })
  
   //Update the meta for a Wishlist
   app.patch('/wishInfo/:gamename', async (req, res) =&gt;{
  
      let gPatch = await Wishlist.update(
          {
              gamename: req.body.gamename,
              gameid: req.body.gameid,
              star: req.body.star,
              review: req.body.review,
              username: req.body.username, 
           },    {
                    where:{
                        gamename: req.params.gamename
                    }
                } 
          
      )
      res.sendStatus(200).send(gPatch);          
   })
  
   // User login 
  app.post('/login', (req, res) =&gt; {
      const { email, password } = req.body;
  
      models.User.findOne({
          where: { email: email }
        }).then((user) =&gt; {
          if (!user) {
            res.json({ error: 'no user with that username' })
            return;
          }
      
          bcrypt.compare(password, user.password, (err, match) =&gt; {
            if (match) {
              req.session.user = user;
              res.json({ user_id: user.id, success: true })
            } else {
              res.json({ error: 'incorrect password' })
            }
          })
        })
      })
  
  
  app.listen(8500, async ()=&gt; {
      console.log('Server is running on port 7500')
      await sequelize.sync()
  })</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
      &lt;meta charset="UTF-8"&gt;
      &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
      &lt;title&gt;Response Page&lt;/title&gt;
    
  
  &lt;/head&gt;
  &lt;body&gt;
      
          &lt;div class="flexbox"&gt;
      
              &lt;header class="header"&gt;
                 
       
  
          &lt;nav class="navbar navbar-expand-lg navbar-light bg-light"&gt;
              &lt;div class="container-fluid"&gt;
                &lt;a class="navbar-brand" href="./index2.html"&gt;Gamz+&lt;/a&gt;
                &lt;button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"&gt;
                  &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt;
                &lt;/button&gt;
                &lt;div class="collapse navbar-collapse" id="navbarSupportedContent"&gt;
                  &lt;ul class="navbar-nav me-auto mb-2 mb-lg-0"&gt;
                    &lt;li class="nav-item"&gt;
                      &lt;a class="nav-link active" aria-current="page" href="./FavoritesWish.html"&gt;Favorites&lt;/a&gt;
                    &lt;/li&gt;
                    &lt;li class="nav-item"&gt;
                      &lt;a class="nav-link" href=""&gt;Page 2&lt;/a&gt;
                    &lt;/li&gt;
                    &lt;li class="nav-item"&gt;
                      &lt;a class="nav-link" href=""&gt;Page 3&lt;/a&gt;
                    &lt;/li&gt;
                    &lt;li class="nav-item dropdown"&gt;
                      &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"&gt;
                        Dropdown
                      &lt;/a&gt;
                      &lt;ul class="dropdown-menu" aria-labelledby="navbarDropdown"&gt;
                        &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt;&lt;/li&gt;
                        &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt;
                        &lt;!-- &lt;li&gt;&lt;hr class="dropdown-divider"&gt;&lt;/li&gt;
                        &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; --&gt;
                      &lt;/ul&gt;
                    &lt;/li&gt;
                    &lt;li class="nav-item"&gt;
                      &lt;a class="nav-link disabled"&gt;Disabled&lt;/a&gt;
                    &lt;/li&gt;
                  &lt;/ul&gt;
                  &lt;form method="POST" action="/home" class="d-flex"&gt;
                    &lt;input name="search" class="form-control me-2 search-button" type="text" placeholder="Search" aria-label="Search"&gt;
                    &lt;button  class="btn btn-sm btn-block btn-primary mt-auto" type="submit"&gt;Search&lt;/button&gt;
                  &lt;/form&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/nav&gt;   
      &lt;/header&gt;
      
  
      &lt;div&gt;
  
    &lt;div class="card" style="width: 18rem;"&gt;
      &lt;img src="${game.background_image}" class="card-img-top" alt="" width="100" height="120"&gt;
      &lt;div class="card-body"&gt;
        &lt;h5 id="title" class="card-title"&gt;${game.name} &lt;/h5&gt;
        &lt;p class="card-text"&gt;Platform ${game.parent_platforms.map((platform)=&gt;{
          return platform.platform.name
        })}  &lt;/p&gt;
      &lt;/div&gt;
      &lt;ul class="list-group list-group-flush"&gt;
        &lt;li class="list-group-item"&gt;Rating ${game.rating}&lt;/li&gt;
        &lt;li class="list-group-item"&gt;Game ID ${game.id}&lt;/li&gt;
        &lt;li class="list-group-item"&gt;Release Date ${game.released}&lt;/li&gt;
      &lt;/ul&gt;
      &lt;div class="card-body"&gt;
        &lt;a id="fav" href="#" class="card-link"&gt;Add to Favorites&lt;/a&gt;
        &lt;a id="wish" href="#" class="card-link"&gt;Add to Wishlist&lt;/a&gt;
      &lt;div class="input-group mb-3"&gt;
          
          &lt;button class="btn btn-outline-secondary" type="button" id="button-addon2"&gt;Add to Favorite&lt;/button&gt;
      &lt;/div&gt; 
      &lt;/div&gt;
    &lt;/div&gt;
    
    &lt;/div&gt;
  
  
   
      
  
  
      &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"&gt;
      &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"&gt;&lt;/script&gt;
      
      &lt;script src="serverBP.js"&gt;&lt;/script&gt;    
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>