我是JavaScript
的初学者,正在努力通过使用基于Ajax
的GET/ POST
请求从某些Node.js
后端代码发出相同的请求。我使用MySQL
数据库。我已经通过一些教程并获得一些理解。例如,Ajax POST
请求可能是这样的,将Node.js GET/POST请求更改为Ajax
$.ajax({
url: '/walletinfo',
method: 'POST',
data: {
name: addressName,
address: wallet.getAddress()
},
success: function(result) {
console.log(result)
},
error: function(err) {
console.log(err)
}
})
的Node.js POST
请求,我有提供,
// 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)
});
})
因此,它似乎req
对象集结SQL
查询和con.query
尝试执行它。如果INSERTION
按预期完成,我们将嵌入res
与result
。
看来我必须做一些data: { name: addressName, address: wallet.getAddress() }
部分的$.ajax
请求,并在那里拨打con.query
。
我也有一个GET
请求从Node
更改为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)
});
})
如何正确地做到这一点?
从Node到Ajax的确切含义是什么?你在寻找如何使用Ajax来请求他们吗? – y0hami
是的,更新语言,并希望它会有所帮助。顺便说一下,“英语”不是我的第一语言。 – Arefe
那么你想用网页中的Ajax请求这些端点('/ walletinfo')吗? – y0hami