I'm trying to post data to an MySQL database by using Node.js.
This is my htmlHTML form:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>form</title> </head> <body> <h1>This is my form</h1> <!-- local host to be changed? --> <form action="http://localhost:3000/index.html" method="POST"> First name:<br> <input type="text" name="firstname" value="John"> <br> Last name:<br> <input type="text" name="lastname" value="Doe"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
And here is my MySQL.js
:
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'mysqlhost',
port : '3306',
user : 'myuser',
password : 'mypassword',
database : 'myuser'
} ); connection.connect(); var query = connection.query('SELECT * FROM http://localhost:3000/index.html');
query.on('error', function(err) {
throw err; });
query.on('fields', function(fields) {
console.log(fields); })
query.on('result', function(row) {
console.log(row); }); connection.end();
Is this even possible?
Yes, this is possible, but you're definitely not going into the right direction. I suggest learning how to make a simple REST API Node app to get started. This tutorial is a good starting point. I suggest using Express as it simplifies the task of handling POST/GET requests.
Here is starter code that does what you want.
Note how I used /data
instead of localhost:3000/index.html
in the <form action=...>
part. This is generally known as a REST api.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>form</title>
</head>
<body>
<h1>This is my form</h1>
<!-- local host to be changed? -->
<form action="/data" method="POST">
First name:<br>
<input type="text" name="firstname" value="John">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
var app = require('express')();
var bodyParser = require('body-parser');
var path = require('path');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/data', function(req, res) {
console.log(req.body.firstname);
console.log(req.body.lastname);
// Add these values to your MySQL database here
});
app.listen(3000);
app.js
index.html
npm install express
npm install body-parser
node app.js
Then simply go to localhost:3000
in your browser.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.