【问题标题】:How to access the data I post from client-side (NodeJs)如何访问我从客户端(NodeJs)发布的数据
【发布时间】:2020-04-14 08:09:11
【问题描述】:

我在JS中收集了一些数据;

var dataset = {
    "name" : undefined,
    "pass" : undefined,
    "email" : undefined,
    "birthday" : undefined,
    "agree" : false
}

function data () {

    dataset = {
        "name" : document.getElementsByName("name")[0].value,
        "pass" : document.getElementsByName("pass")[0].value,
        "email" : document.getElementsByName("email")[0].value,
        "birthday" : document.getElementsByName("birthday")[0].value,
        "agree" : false
    }

    if(document.getElementById("signupcheck").className.search("active") > -1) dataset.agree = true;

}

并且有一个 NodeJs 页面

var express = require("express");
var app = express();

app.use(express.static('public'));

app.get("/",function(req,res){
    res.sendFile(__dirname + "/index.html");
})

我想将数组“数据集”发布到服务器端,并在 NodeJs 页面中访问,但我不能。我尝试像在代码中一样使用 Ajax 发送,但失败了:

const xhttp = new XMLHttpRequest();
xhttp.open("POST", "/example");
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send("name=weweww&urd=sss");

NodeJs:

app.post("/example", function(req,res) {
  console.log(req.body)
})

它在终端上返回“未定义”。 如何访问我从客户端发布的数据?

【问题讨论】:

    标签: javascript node.js ajax express


    【解决方案1】:

    需要使用node js的body-parser模块获取req.body中的数据

    npm install body-parser
    

    app.js

    var bodyParser = require('body-parser')
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    

    更多详情

    Express body parser Body-parser NPM

    【讨论】:

    • 还有一个问题,当我发布 xhttp.send(dataset) 之类的数据时,它返回一个空对象。哪个函数能解决问题?
    • 这是您的 xhttp 请求的问题,您可以对其进行调试以确保您发送的数据不是空对象
    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 2021-10-07
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多