【问题标题】:Can't find the data that's sended by using Ajax in the request object (Nodejs)在请求对象(Nodejs)中找不到使用 Ajax 发送的数据
【发布时间】:2020-04-13 11:30:19
【问题描述】:

我在代码中发送一个数据对象;

var xhttp = new XMLHttpRequest();
var dataset;

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
    xhttp.open("POST", "/example", true);
    xhttp.send(dataset);
}

我尝试在代码中获取 NodeJs 上的数据;

var express = require("express");
var app = express();
var router = express.Router();

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

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

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

var server = app.listen(8000,function(){

})

Ajax 正在工作,因为我在初始化函数时可以在控制台上看到 req 对象。但是 req 对象太大了,不适合终端。

我找不到我发送的数据。如何获取数据?

【问题讨论】:

    标签: node.js json ajax express


    【解决方案1】:

    所以我认为问题在于您的请求。

    在本地运行后我得到:

    TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of Object
    

    查看文档后,它证实了这一点https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

    你可以试试这个吗?

    xhttp.send(JSON.stringify({dataset: dataset}))
    

    或者您可以将数据集对象更新为

    const dataset = {
        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,
        },
    }
    

    并保持

    xhttp.send(dataset)
    

    添加 express json 中间件,以便您可以访问正文。

    const express = require('express')
    
    const app = express()
    const router = express.Router()
    
    app.use(express.json())
    
    console.log(req.body.dataset)
    

    【讨论】:

    • 返回“未定义”。
    • 你能用请求的控制台日志更新帖子吗?你在使用 bodyParser 和 express 吗?
    • 我做到了,但我认为它没用,因为该对象不适合终端。
    • 当我写“req.body.dataset”时,我收到两个错误,“POST localhost:8000/example500(内部服务器错误)”和“未捕获的 TypeError:无法设置属性 'innerHTML' of null at XMLHttpRequest.xhttp.onload”。当我写“req.body”时,我得到“未定义”的结果,我没有收到任何错误。
    • 无法设置属性 'innerHTML' - 这与您发布的请求或路由无关。尝试更新文档中的 html 时,您必须在其他地方出现错误。您要么必须发布所有代码,要么自己查找问题。我在本地尝试过,效果很好。
    猜你喜欢
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2013-08-28
    • 2014-09-26
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多