skip to Main Content

I am using node/express and EJS, along with postgres database.

I have 3 inputs in my home.ejs file named:
title, platform, genre.

These are contained in a form so I can create a post request.

and looks like this:

<h2>Add a Game:</h2>
  <form method="POST" action="/">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" required><br><br>
    <label for="platform">Platform:</label>
    <input type="text" id="platform" name="platform" required><br><br>
    <label for="genre">Genre:</label>
    <input type="text" id="genre" name="genre" required><br><br>
    <button type="submit">Add Game</button>        
  </div>

The values entered into these inputs are sent as a post request to my server file (app.js)

app.post('/', async (req, res) => {

// get the user's input from the form
const title = req.body.title;
const platform = req.body.platform;
const genre = req.body.genre;

The values are then assigned to variables in above code.

From within this post route i am then trying to pass these values to my api.js file that is basically a case statement of API’s with the following arguments:

app, pool, user_id, apiName;

The file is imported into my app.js by the below line:

 const apiList = require('./routes/api_list');

Using the code line below I pass these arguments into my API case statement:

const result = await apiList(app, pool, 1, 'addNewGame', {title, genre, platform });

The particular API I am targeting should take these values and insert them to my postgres database.

Part of my API looks like this:

case 'addNewGame':
return new Promise(async (resolve, reject) => {
try {
  const {title, genre, platform } = req.body;
  const result = await pool.query('INSERT INTO schemaName,tableName(user_id, title, genre, 
  platform) VALUES ($1, $2, $3, $4)', [userId, title, genre, platform]);

  if (result.rowCount === 0) {
    reject('exists'); // Reject the promise with 'exists' if the game already exists
  } else {
    resolve('added'); // Resolve the promise with 'added' if the game is successfully added
  }

My console logs an error saying:

TypeError: Cannot destructure property ‘title’ of ‘req.body’ as it is
undefined.
at fileLocationroutesappList.js:75:14
at new Promise ()

I have tried retrieving the values from the request data object and made sure i also passed this object in as an argument in my app.js post route, but had the same console error saying requestData is not defined.

Things to Note:
I already have the "read" part of my CRUD working, and have successfully send data from my DB to the front end, therefore there are no errors in my DB connection.

I have the following declared in app.js file:

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

I have been asked by ‘Ivan‘ to show the apiList case statement method, see below;

module.exports = function(app, pool, userId, functionName, req) {
switch (functionName) {
case: 'addGame':

Any help would be greatly appreciated!

3

Answers


  1. Chosen as BEST ANSWER

    Thanks Ivan, your answer lead me to find the solution, i also needed to change the below code in my app.js post route:

    const result = await apiList(app, pool, 1, 'addNewGame', {title, genre, platform 
    });
    

    to this:

    const result = await apiList(app, pool, 1, 'addNewGame', req);
    

    This has fixed the issue.


  2. I think that You have Not used body parser package to parse the body that is coming in post request from api
    Add below code in top of js file so that it will help you for reading the data from post request

    const bodyParser = require('body-parser');
    app.use(bodyParser.json()); 
    app.use(bodyParser.raw());
    
    Login or Signup to reply.
  3. Based on supplied information your method doesn’t have req input parameter.

    module.exports = function(app, pool, userId, functionName) {
    switch (functionName) {
    case: 'addGame':
    

    And that is what error is saying

    ReferenceError: req is not defined at
    folder_directoryroutesapi_list.js:74:41

    In order to fix this you need to modify your method signature to:

    module.exports = function(app, pool, userId, functionName, req) {
    switch (functionName) {
    case: 'addGame':
    

    It seems to me that you are calling method correctly, because you have 5 input parameters:

    const result = await apiList(app, pool, 1, 'addNewGame', {title, genre, platform });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search