I'm a beginner in JavaScript
and working to make the same request from some Node.js
backend code to by using the Ajax
based GET/ POST
requests. I use MySQL
database. I have gone through some tutorials and get some understanding. For example, an Ajax POST
request could be something like,
$.ajax({
url: '/walletinfo',
method: 'POST',
data: {
name: addressName,
address: wallet.getAddress()
},
success: function(result) {
console.log(result)
},
error: function(err) {
console.log(err)
}
})
The Node.js POST
requests that I have is provided,
// initiations of the code
const express = require('express')
const path = require('path')
const bodyParser = require("body-parser");
const mysql = require('mysql');
const app = express()
const con = mysql.createConnection({
host: "localhost",
user: "testuser",
password: "testpassword",
database : 'wallet1'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.use('/', express.static(path.join(__dirname, 'public')))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// initiations of the code
app.post('/walletinfo', function (req, res) {
var sql = "INSERT INTO wallet_info (name, address) VALUES ('" + req.body.name +"', '" + req.body.address + "')";
con.query(sql, function (err, result, fields) {
if (err) console.error(err);
res.json(result)
});
})
So, its seems that the req
object build-up the SQL
query and the con.query
tries to execute it. If the INSERTION
is done as expected, we embedded the res
with the result
.
It seems I have to do something with the data: {
name: addressName,
address: wallet.getAddress()
}
part of the $.ajax
request and make the con.query
call over there.
I also have a GET
request to change from Node
to the Ajax
,
app.get('/walletinfo', function (req, res) {
con.query("SELECT * FROM wallet_info", function (err, result, fields) {
if (err) throw err;
console.log(result);
res.json(result)
});
})
How to do it properly?
Copyright Notice:Content Author:「Arefe」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45480631/change-the-node-js-get-post-requests-to-the-ajax