1

I'm new with nodeJs, I'm trying to send data from my form to DataBase using nodeJs but I didn't understand what I have to do I found many codes on the internet but no one works.Can anyone explain to me what I have to do?

thank you.

1
  • check this package Commented Dec 19, 2017 at 12:29

1 Answer 1

1

Here's an example of how to save data passed from html form into your mysql database:

first install these packages:

npm install --save mysql body-parser

body-parser Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Then we will create a simple form with one input field assuming we are collecting only the user email

Your form

<form method="POST" action='/register'>
 <input type="text" name="email" class="form" placeholder="Enter Your Email">
 <button>Join Now</button>
</form>

Then you will need to setup some route handler to handle the submission of the form here we will create a route handler for /register to save an email

Your app.js

const express = require("express");
const mysql = require("mysql");
const bodyParser = require("body-parser");
const app = express();


app.use(bodyParser.urlencoded({extended: true}));

const connection = mysql.createConnection({
  host: "localhost",
  user: "username",
  database: "database_name",
  password : 'your_password'
});

app.post('/register', function (req, res) {
    const email = req.body.email;

    const data = { 
        email
    };

    connection.query('INSERT INTO table_name SET ?', data, function (error, results, fields) {
      if (error) throw error;
      res.send('Email inserted successfully');
    });
});

app.listen(8080, function() {
    console.log('Server is running on port 8080...');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you things are more clear to me , but the insert is not working my data base is empty .
You need to provide your database credentials otherwise it should throw an error in the console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.