purpose: use nodejs to insert the data returned from the front end into the table in mysql
Code logic:
-sharp-sharp1, front page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<!-- <form action=""> -->
<label for="id">id</label>
<input type="text" name="name" id="id">
<label for="name"></label>
<input type="text" id="name">
<label for="price"></label>
<input type="text" id="price">
<input type="submit" value="" id="submit">
<!-- </form> -->
<input type="file" name="" id="" accept="image/*">
</body>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$("-sharpsubmit").click(() => {
$.ajax({
type: "post",
url: "http://localhost:3001/",
data: {
id: $("-sharpid").val(),
name: $("-sharpname").val(),
price: $("-sharpprice").val()
},
datatype: "json",
success: function (res) {
console.log(res)
},
error: function (err) {
console.log(err)
}
})
})
</script>
</html>
< H2 > 2, backend page < / H2 >
connction.js
var connction = {};
connction.mysql = {
host: "localhost", //
user: "root", //
password: "******.", //
database: "T2" //
} //
////////////////////
module.exports = connction; //module.exports
Interface index.js
var express = require("express");
var router = express.Router();
var mysql = require("mysql");
var sql01 = require("./../connction");
// DBConfig.jsMySQL
var pool = mysql.createPool(sql01.mysql);
// var $sql = $mysql.createConnection(sql01.mysql) // mysql
// $sql.connect()
// JSON
// var responseJSON = function (res, ret) {
// if (typeof ret === "undefined") {
// res.json({
// code: "-200",
// msg: ""
// });
// } else {
// res.json(ret);
// }
// };
//
router.post("/", function (req, res, next) {
// console.log(req )
//
pool.getConnection(function (err, connection) {
//
var param =req.body;
var addSql = "insert into goods(id,name,price) values (?,?,?)";
var hh = [param.id,param.name,param.price];
console.log(param) //
//
connection.query(addSql,hh, function (err, result) {
console.log(result)
if (result) {
result = {
code: 200,
msg: ""
};
}
// json
// responseJSON(res, result);
//
connection.release();
});
});
});
/* GET home page. */
router.get("/", function (req, res, next) {
res.send("halll")
});
router.get("/login", function (req, res, next) {
res.send("this is index/login page")
})
module.exports = router;