我想将candid和candidresults的值发送到我的快速后端的/ savevote路由中。我该怎么做。
var candid;
var candidresults;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'savevote', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
contractInstance.voteForCandidate(candidateName, {
from: web3.eth.accounts[0]
}, function () {
console.log(contractInstance.totalVotesFor(candidateName).toString());
candid = candidateName;
candidresults = contractInstance.totalVotesFor(candidateName).toString();
console.log(this.responseText);
};
xhr.send(candid);
xhr.send(candidresults);
}
而且,我如何通过我在Express后端下面创建的/ savevote路由访问这些值,如下所示
router.post('/savevote', function (req, res, next) {
});
在您的快递上,您需要使用中间件才能从req.body
读取参数
下面是示例代码
const express = require('express')
const app = express()
app.use(express.urlencoded())
app.post('/savevote', (req, res) => {
res.json({
msg: "Echo respose"
candid: req.body.candid,
candidresults: req.body.candidresults
})
})
app.listen(3000)
而且,从用户界面中,您无法多次调用xhr.send
。只能调用一次,如下所示
xhr.send("foo=bar&lorem=ipsum");