Search code examples
node.jspostgresqlexpress

How to pass the value of a req.body.name from post route in app.js to an API endpoint in a module.exports js file


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 fileLocation\routes\appList.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!


Solution

  • 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_directory\routes\api_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 });