【问题标题】:How to read values sent in Xmlhttprequest POST request on my express backend in Nodejs?如何在我的 Nodejs 快速后端读取 Xmlhttprequest POST 请求中发送的值?
【发布时间】:2019-12-10 11:19:08
【问题描述】:

我想将 candidcandidresults 的值发送到我的 express 后端中的 /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访问帖子参数

标签: javascript node.js express xmlhttprequest http-post


【解决方案1】:

在你的快递上,你需要使用中间件来读取来自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)

另外,从 UI 中,您不能多次调用 xhr.send。 它应该只调用一次,如下所示

xhr.send("foo=bar&lorem=ipsum");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多