我在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())
了解更多详情
关于javascript - 如何访问我从客户端(NodeJs)发布的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61203261/