Utilize Express.js api and the mysql package to upload an array into MySQL Workbench

Struggling with setting up Express.js and the mysql package for creating APIs, I find myself unable to execute a POST request.

This is the current state of my code:

const express = require('express');
const mysql = require('mysql');

const config = mysql.createConnection({
    host: theHost,
    port: thePort,
    user: theUser,
    password: thePass,        
    database: theDB,
});

const app = express();

config.connect(function(err){
    if(!err) {
        console.log("Success");

    } else {
        console.log("Error trying to connect");    
    }
});

app.get("/api/InternalAccess", function(req, res){
    config.query('SELECT * from InternalAccess', (error, result) => {
        if (error) throw error;

        res.send(result);
      });
});

app.post("/api/internalAccess", function(req, res){

    var info = { User: req.body.User, Password: req.body.Password, CreationDate: req.body.CreationDate };

    config.query('INSERT INTO InternalAccess SET ?', info, (error, result) => {
        if (error) throw error;

        res.send(result);
      });
});

app.listen(3000);

While getting data using GET works perfectly, attempting to make a POST request in Postman throws an error: "Cannot read property "User" of undefined". What am I missing? I'm quite new to using the mysql package.

The database I'm working with is MySQL Workbench, alongside Node.js, Express.js, and the mysql package.

I would greatly appreciate any help or insights. Thank you in advance.

Answer №1

If you want req.body to be automatically populated, make sure to include the necessary body-parser middlewares in your Express app:

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

There could be other reasons why it's not working (like incorrect request setup in postman), but setting up these middlewares is a good first step.

Answer №2

It appears that the variable req.body is null. It is possible that you have overlooked adding the body-parser in your app.js file.

var bodyParser = require('body-parser');

var app = express();

// ensure proper parsing of application/json
app.use(bodyParser.json())

For more examples, please visit: https://expressjs.com/en/resources/middleware/body-parser.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing `npm install --save`, it is important to understand the significance of saving the installed

Although I grasp the distinctions between npm install something and npm install something --save (just to clarify, the former only installs the dependency while the latter also adds it to your package.json), I find myself puzzled by the existence of the -- ...

The React component embedded in the HTML does not render on the webpage after making a 'get' request in Node.js

Currently, I am delving into the world of web development and utilizing Visual Studio Code for my projects. To kick things off, I created a React app by running the command 'npx create-react-app my-app' which worked smoothly. As I progressed wi ...

The Mysql SELECT function is causing an error by returning an unidentified column in the field list

There seems to be an error in my code, even though I have thoroughly reviewed it. This is the code snippet I'm referring to... function add_product_to_cart($pdo, $table, $cart_id, $product_id, $attributes){ $parameters = [':product_id' ...

Exploring the Best Practices for Secure Access Token Management

I have embarked on creating a straightforward API to serve as the backend for my app. Currently, I am in the process of designing my data structures and I find myself pondering about security best practices. Project Details The project is being developed ...

The objects-to-csv module encountered an error: fs.existsSync is not a valid function for this

"TypeError: fs.existsSync is not a function" Whenever I try to create a CSV file and input some data into it, this error message pops up. const objectstocsv = require('objects-to-csv'); export default { data () { return { ...

Accessing secure managed Redis using Node.js authentication credentials

Upon further reflection, the question that arises is how to connect to digitalocean's managed redis with node-redis using tls. Although I can establish a connection with the redisinsight GUI client using a username and password without any issues, I ...

Establish a secure connection tunnel using ngrok to connect to a local MongoDB database

Looking to establish a connection tunnel between two computers. Computer 1 : Frontend (React) Computer 2 : Backend API with MongoDB local database and NodeJS server We attempted to use ngrok for creating the tunnel so my partner can test/build a connect ...

Is there a way to transfer data from one table to another using PHP?

I am facing an issue with copying data from one table to another in my MySQL database named "csv". There are two tables, "Daten" and "Server", both of which have a column named "ServerID". I need to copy the data from the "ServerID" column in the "Server" ...

React and Express facing CORS header challenge

I'm facing an issue with CORS despite trying various solutions found on Stack Overflow. My app uses Express/NodeJS as an API and React JS for the frontend. During development, the React app at http://localhost:3000 communicates successfully with the ...

The package "@sailshq/socket.io-redis@latest" cannot be found on the npm registry

Node version: 10.16.0 Sails version (sails): 1.2.3 Every time I attempt to initiate a new project using the sails cli, I encounter the following error message which prevents me from proceeding further. Additionally, I have come across a package https://w ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

What is causing the error to occur when attempting to deploy my Node.js application that incorporates MongoDB and Mongoose with Express?

Having trouble deploying my app on Render, I keep getting this error. It works flawlessly on my own computer but for some reason won't cooperate when trying to deploy. Feeling stuck and unsure of what to do next, which is pretty rare for me. Any assis ...

File parsing in Node now supports handling merged cells from Excel spreadsheets

Dealing with a variety of excel files can be challenging, especially when some are in disarray and with multiple sheets that I have no control over since they are provided externally. While I've successfully used xlsx-to-json for standard data rows, ...

An exemplary chat application that utilizes sessions for user authentication in a node.js environment with socket.io and express

Is there an example available that stores sessions and uses those sessions for all opened windows, allowing one user to connect to a specific room only once? This application will treat phpsessions as node.js sessions, but I am struggling to restrict acce ...

Passing Private Data Between NodesIs it possible for a node to

In my Express route (item/update/), after processing, I intend to redirect the user back to /. Furthermore, I would like to display an alert on / indicating either 'Success' or 'Failure'. To achieve this, without exposing data through q ...

Error 404 - Bootstrap not found in Bower Components

I've scoured the internet and checked multiple forums, but I haven't been able to find a solution that works for me. My Node project has a specific structure: ├── app │   ├── config │   │   ├── env │   │   ...

Using two variables

Whenever I use my select function and pass in two variables (the table and the condition), it always displays id = 1 no matter what condition I provide. I'm wondering if this happens because the function recognizes that "id" already has a default val ...

Is it possible for me to customize the MySQL query based on the user input using PHP?

I am facing a unique situation where the query depends on user input. When the user enters "toy," the query includes certain conditions, and when they enter "TV," the query changes slightly. This method works fine for a few products, but I have many diff ...

Issue with PlayWright HTML report not being served in a Docker container

I am currently executing my PlayWright tests from a docker container to validate my ReactJS application Everything is functioning as expected, and a report directory is created successfully In the event that some tests fail, PlayWright attempts to disp ...

ERROR: "The Mongoose server selection process encountered a problem and was unable to establish a connection to any servers within your MongoDB Atlas cluster."

I am experiencing issues connecting mongoose with my application. An error message is displayed as follows: "MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason for this error is attempting to acc ...