Unable to submit form in Node.js with Express

I am just starting out with node.js and I need help with a sample form to insert values into a database.

Below is the code snippet for my test page:

<form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencoded">
     <input type="text" id="username_input" name="username">
     <input type="text" id="password_input" name="password">
     <input type="submit" name="Submit" value="Insert" class="btn">
</form>

Attempting to post the form data:

I have created a test.js file and implemented the post method as follows:

exports.list = function (req, res) {
    req.getConnection(function (err, connection) {
        console.log(con)
        app.post("/create", function (req, res) {
            var username = req.body.username,
     password = req.body.password;
            console.log(username);
            console.log(password);

            connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {

                if (error) {

                    console.log(error.message);
                } else {
                    console.log('success');

                }

            });

        });
    });
}

However, this approach did not work. I also tried implementing the post method directly in the main server.js file:

app.post("/create", function (req, res) {
        var username = req.body.username,
 password = req.body.password;
        console.log(username);
        console.log(password);

        connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {

            if (error) {

                console.log(error.message);
            } else {
                console.log('sucess');

            }

        });

    });

This attempt was also unsuccessful. I have provided the current settings from my server.js file below:

/**
* Module dependencies.
*/

var express = require('express')
  , routes = require('./routes')
  , index_form = require('./routes/index_form')
  , user = require('./routes/user')
  , test = require('./routes/test')
  , mysql = require('mysql')
  , http = require('http')
  , path = require('path')
  , mongoose = require('mongoose');

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'pass@123'
});

var app =express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function () {
    app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/test', test.test);
app.get('/users', user.list);
app.get('/index_form', index_form.index_form)

http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});

I would greatly appreciate your guidance on how to successfully post a form using node.js.

Answer №1

Have you attempted inserting app.post("/create", test.test); into your existing server.js following the GET routes? It seems that your current server.js is lacking any POST requests based on what I came across.

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

Incorporating Angular 6 and NodeJS 8.4 with the MEAN stack, I aim to display the current status of all identifiers stored in MongoDB directly onto the browser

After successfully storing the list of objects in MongoDB, I have implemented a functionality to display all items on the browser. When the inventory button is clicked, the routerlink is used to fetch the availability and list them accordingly. Now, I am ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

The nodejs express application encountered a CSRF token mismatch when attempting to make an ajax post request

Software Stack: Node.js, MongoDB, Handlebars, Bootstrap In controllers/products/index.js module.exports = function (router) { router.post('/add',function(req,res){ // implementation logic }); }; On the website, users can add pr ...

What causes errors to occur with create react app?

Recently, I have been working on building a React app. After installing Node.js, I attempted to run the command npx create-react-app .. However, I encountered an issue as it did not work properly. Here is a screenshot from my command prompt showing the v ...

What methods can be used to validate try-catch code in JavaScript with Jest, and how can a next() call be incorporated with middleware in

Currently, I am in the process of creating an API and one of my tasks involves testing a try-catch block. My main objective is to ensure that any errors caught by the block are passed through 'next()' in Express to reach the next middleware. To ...

The D3js visualization is failing to display properly for the user, with the D3 source code residing on the server

I have encountered an issue after transferring my D3js chart generation system from a development server with no problems to a live Windows 2008 r2 server. On the live server, only the background SVG element is displayed and none of the other elements like ...

Attempting to execute a shell script through node.js while utilizing the sudo -S command

I am facing an issue while trying to use sudo access to run a shell script on Mac that executes a python script using Node.js. I found some information on How to run shell script file using nodejs? which was helpful, but now I am stuck: Shell script: #!/ ...

Troubleshooting a JavaScript error while attempting to execute a function from a

I have been working on a new JavaScript library named TechX. Check out the code snippet below: (function(){ function tex(s){ return new tex.init(s); }; //initiate the init selector function tex.init = function(s ...

Express error handler failed to catch the validation error

I have a field type in my mongoose schema that is required. I've implemented a custom error handler in express like this: const notFound = (req, res, next) => { const error = new Error(`Not found-${req.originalUrl}`); res.status(404); next(er ...

Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag: $(document).ready(function(){ var FamilyTree = function() { }; FamilyTree.prototype.displayMessage=function() { alert("test"); } }); Then, within the bo ...

Showcasing unique <div> content after a delay with setTimeout()

Within this code snippet, I am utilizing a setTimeout() function to make an API call to my backend node.js application every 5 seconds. The AJAX success section determines when to display divContent1 and divContent2 based on specific conditions that must b ...

muiSlider limited to specific range

I am currently using the Mui Slider component for a user interface where I need to restrict its value within a certain range. For example, I want the slider's handle to become unmovable after reaching 50. Users can still select values up to 50, but th ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Caution: React alert for utilizing the UNSAFE_componentWillReceiveProps in strict mode

As a newcomer to React, I encountered a warning that has me stuck. Despite researching extensively online, I still can't resolve it. The warning message is: https://i.stack.imgur.com/4yNsc.png Here are the relevant portions of the code in App.tsx: ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

Blend Mode / Vue CLI / Remote server routing

I'm looking for a solution to set up a proxy in an AngularCLI/Webpack environment. The main goal is to forward requests from http://localhost:4200/rest to https://someserver.com/somepath/rest. One challenge is that the endpoint is using HTTPS instead ...