Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError on server response when using Node.js and MySQL

Tags:

node.js

mysql

I'm having trouble to post form data from my html file into MySQL. I keep getting a syntax error on the server response and the data does not save on the MySQL database. I have posted the code and error below. I'm struggling to resolve this issue.

Error in server response

TypeError: this._callback.apply is not a function at Query.Sequence.end

index.html

<form action="/" method="post">
    <input id="name" type="text" name="name" placeholder="Type your name...">
    <input id="message" type="text" name="message" placeholder="Type message...">
    <input class="submit_message" type="submit" value="Send">
</form>

server.js

var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));

var connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mywebsite"
});

connection.connect();

app.get('/',function(req,res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/', function(req, res) {
    var username = req.body.name;
    var usermessage = req.body.message;
    connection.query("INSERT INTO `users` (Name, Message) VALUES (?)", username.toString(), usermessage.toString(), function(err, result) {
        if(err) throw err;
            console.log("1 record inserted");
        });
    res.send(username + " - " + usermessage);
});

connection.end();

app.listen(3000, function () {
    console.log('Listening on port 3000');
});

1 Answers

When using placeholder values in connection.query, they must be an array of values or an object. But you're passing each value as a different argument, and one of them is being used as the callback parameter, that's why you get that error.

.query(sqlString, values, callback)

Use this instead:

connection.query("INSERT INTO `users` (Name, Message) VALUES (?,?)", [username.toString(), usermessage.toString()], function(err, result) {})

Or using named placedholders

const placeholders = { name: username.toString(), message: usermessage.toString() };

connection.query("INSERT INTO `users` (Name, Message) VALUES (:name,:message)", placeholders, function(err, result) {})
like image 66
Marcos Casagrande Avatar answered Dec 21 '25 13:12

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!