javascript - 如何访问我从客户端(NodeJs)发布的数据

标签 javascript node.js ajax express

我在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)
})

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

最佳答案

需要使用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

关于javascript - 如何访问我从客户端(NodeJs)发布的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61203261/

相关文章:

javascript - 如何计算移动设备上的页面加载时间?

node.js - 无法使用本地主机 URL 和 MongoJS 查询 MongoDB

javascript - 通过 mvc 中的 ajax actionlink 获取成功的响应 header

javascript - HTML DOM 和 XML DOM 有什么区别

javascript - Ajax 程序在 Chrome 上无法运行

node.js - Node Sequelize 关系挑战

jquery - 如何从另一个页面加载背景图像?

jquery - 简单的php ajax请求url

javascript - Facebook Flow 函数联合类型

node.js - Mongoose 查找回调未执行