首页 > 解决方案 > 在 Javascript 和 Express 中从前到后发送数据

问题描述

我创建了一个变量来从我的前端捕获数据,并希望在我的 Express 后端检索它。

我的 js 变量和 POST 请求:

const dataPush = {
                urlSave: urlSave,
                imgSave: imgSave,
                marqueSave: marqueSave,
                smSave: smSave,
                typeSave: typeSave,
                precisionSave: precisionSave,
                yearsSave: yearsSave,
                coteEuSave: coteEuSave,
                coteUsdSave: coteUsdSave,
                coteGbSave: coteGbSave,
                coteChfSave: coteChfSave
            }
            let postIdUrl = String('/fr/post')
            fetch(postIdUrl, {
                method: "POST",
                body: JSON.stringify({"data": "dataPush"}),
                headers: { "Content-Type": "application/x-www-form-urlencoded" }
            })
            console.log(dataPush)

没关系,我得到了我需要的所有数据。

我的快递代码:

router.post('/post', (req, res) => {
    console.log('yep !')
});

如何从dataPush变量中检索数据?

标签: javascriptexpressfetch

解决方案


您的提取请求。删除正在传递的变量上的引号,并可能作为 JSON 传递

fetch(postIdUrl, {
  method: "POST",
  body: JSON.stringify({ "data": dataPush }),
  headers: { "Content-Type": "application/json" }
})

您的端点

router.post('/post', (req, res) => {
    console.log(req.body)
});

推荐阅读