【发布时间】:2018-01-10 20:20:26
【问题描述】:
我是JavaScript 的初学者,正在努力通过使用基于Ajax 的GET/ POST 请求从一些Node.js 后端代码发出相同的请求。我使用MySQL 数据库。我已经阅读了一些教程并获得了一些理解。例如,Ajax POST 请求可能类似于,
$.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。
看来我必须对$.ajax 请求中的data: {
name: addressName,
address: wallet.getAddress()
} 部分做点什么,并在那里拨打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 请求它们?
-
是的,更新了语言,希望对您有所帮助。顺便说一句,
English不是我的第一语言。 -
那么你想通过网页的 Ajax 请求这些端点 (
/walletinfo) 吗? -
是的。这些是相同的,但是,我使用的应用程序有许多不同的端点。
标签: javascript jquery mysql node.js ajax