【问题标题】:Where does data sent using xmlhttp.send() get attached in the POST route in express?使用 xmlhttp.send() 发送的数据在 express 的 POST 路由中附加到哪里?
【发布时间】:2016-09-16 15:31:24
【问题描述】:

我正在通过在我的 javascript 代码中调用此函数来生成 XMLHTTPRequest,如下所示

ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl+'/new-poll/option-entered', value, function(data){
                    console.log(data);
                }));

然后我发出如下所示的实际 xmlhttp 请求

var ajaxFunctions = {
  ready: function ready (fn) {
      if (typeof fn !== 'function') {
         return;
      }

      if (document.readyState === 'complete') {
         return fn();
      }

      document.addEventListener('DOMContentLoaded', fn, false);
  },
  ajaxRequest: function ajaxRequest (method, url, data, callback) {
      console.log('Entered the ajaxRequest function');
      console.log(data);
      var xmlhttp = new XMLHttpRequest();

      xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            console.log('Making the request');
            callback(xmlhttp.response);
         }
      };

      xmlhttp.open(method, url, true);
      xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xmlhttp.send(data);
  }
};

但是当我尝试在 POST 路由中访问下面的数据时,我收到一个错误,因为 req.body 似乎未定义。但是,我的 res.json 工作正常,这意味着我没有以正确的方式访问我传递的数据。

app.route('/new-poll/option-entered')
        .post(function(req, res){
            console.log(req.body.data);
            res.json('Hi I can return data');
        });
};

我承认这个问题可能只是重复,但我似乎无法找到我应该访问通过 xmlhttp.send() 发送的数据的确切位置!检查 MDN 文档后,我认为它可能附加到 req.body,但返回未定义。那么我到底在哪里找到附加的数据,或者我在发送数据的方式上犯了错误,比如设置了错误的 RequestHeader?

【问题讨论】:

  • 你能试试appUrl的值吗?另外,您要发送什么样的数据?
  • 抱歉错过了那行,appUrl 在 ajax-functions.js 中设置为 appUrl = window.location.origin;我正在尝试发送纯文本数据

标签: javascript node.js express xmlhttprequest


【解决方案1】:

您的 Express 服务器中似乎缺少 body-parser 中间件。如果您想使用req.body,则需要将其作为中间件添加到您的 Express 服务器。

摘自Express req.body docs

req.body

包含在请求正文中提交的数据键值对。默认情况下,它是未定义的,并在您使用 body-parser 和 multer 等正文解析中间件时填充。

您需要安装 body-parser,因为它不是 express 软件包的一部分。

npm i --save body-parser

然后在您的路由之前将其添加到您的 Express 服务器,如下所示:

const express = require('express');
const server = express();
const bodyParser = require('body-parser');

const port = process.env.PORT || 1337;

server.use(bodyParser.json()); // allows Content-Type application/json
server.use(bodyParser.urlencoded({ extended: true }); // parses Content-Type x-www-form-urlencoded

// Your routes go here

server.listen(port, () => { console.log(`listening on ${port}`); });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2022-08-09
    • 2021-01-27
    • 2016-08-08
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多