繁体   English   中英

邮递员邮寄请求有效,但 ajax 邮寄无效。 一遍又一遍地检查客户端js

[英]Postman post request works but ajax post does not. Have checked client side js over and over

stackoverflow 上的第一个问题,我需要答案吗? 我的问题是我有一个端点来创建一个项目,当我用 Postman 发送一个 POST 请求时它可以工作。 我正在使用节点和快递:

router.post("/", jwtAuth, (req, res) => {
  console.log(req.body);
  const requiredFields = ["date", "time", "task", "notes"];
  requiredFields.forEach(field => {
    if (!(field in req.body)) {
      const message = `Missing \`${field}\` in request body`;
      console.error(message);
      return res.status(400).send(message);
    }
  });
  Task.create({
    userId: req.user.id,
    date: req.body.date,
    time: req.body.time,
    task: req.body.task,
    notes: req.body.notes
  })
    .then(task => res.status(201).json(task.serialize()))
    .catch(err => {
      console.error(err);
      res.status(500).json({ message: "Internal server error" });
    });
});

当我使用 Postman 发送并且 req 主体使用正确的值记录时,该端点工作。

但是当我发送我的 ajax 请求时,我的服务器代码将 req.body 记录为一个空对象 ('{}')。 因为邮递员工作,我相信问题出在我的客户端 javascript 上,但我找不到问题所在。 我和其他人已经看了一百万次,但就是找不到问题所在。 这是我的客户端 javascript:

//User submits a new task after timer has run
function handleTaskSubmit() {
  $(".submit-task").click(event => {
    console.log("test");
    const date = $(".new-task-date").text();
    const taskTime = $(".new-task-time").text();
    const task = $(".popup-title").text();
    const notes = $("#task-notes").val();
    $(".task-notes-form").submit(event => {
      event.preventDefault();
      postNewTask(date, taskTime, task, notes);
    });
  });
}

function postNewTask(date, taskTime, task, notes) {
  const data = JSON.stringify({
    date: date,
    time: taskTime,
    task: task,
    notes: notes
  });
//Here I log all the data. The data object and all its key are defined
  console.log(data);
  console.log(date);
  console.log(taskTime);
  console.log(task);
  console.log(notes);
  const token = localStorage.getItem("token");
  const settings = {
    url: "http://localhost:8080/tasks",
    type: "POST",
    dataType: "json",
    data: data,
    contentType: "application/json, charset=utf-8",
    headers: {
      Authorization: `Bearer ${token}`
    },
    success: function() {
      console.log("Now we are cooking with gas");
    },
    error: function(err) {
      console.log(err);
    }
  };
  $.ajax(settings);
}

handleTaskSubmit();

我会怎么做:

  1. 将标题“application/json”更改为“application/x-www-form-urlencoded”,因为 官方文档没有关于前一个的信息。

  2. 停止使用 $.ajax 并适应 XHR 请求,因为当 CDN 延迟时,来自 CDN 的 jquery 有时会一团糟,而 XHR 是本机实现并立即可用。 是的,这是代码混乱,但您总是知道这不是内部库逻辑的问题,而是您自己的问题。 您盲目使用库,将 XHR 隐藏在内部,并且您不知道如何提出正确的问题“XHR post 方法文档”,因为您还不熟悉底层的基本技术。

保存并导入变量

var httpClient = {

        get: function( url, data, callback ) {
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                var readyState = xhr.readyState;

                if (readyState == 4) {
                    callback(xhr);
                }
            };

            var queryString = '';
            if (typeof data === 'object') {
                for (var propertyName in data) {
                    queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
                }
            }

            if (queryString.length !== 0) {
                url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
            }

            xhr.open('GET', url, true);
            xhr.withCredentials = true;
            xhr.send(null);
        },

        post: function(url, data, callback ) {
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                var readyState = xhr.readyState;

                if (readyState == 4) {
                    callback(xhr);
                }
            };

            var queryString='';
            if (typeof data === 'object') {
                for (var propertyName in data) {
                    queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
                }
            } else {
                queryString=data
            }

            xhr.open('POST', url, true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(queryString);
        }
    };

用法和jquery一样简单:httpClient.post(Url, data, (xhr) => {})

  1. 检查您是否在 app.js 中设置了正文解析器

    var bodyParser = require('body-parser'); app.use(bodyParser.json()); // get information from html forms app.use(bodyParser.urlencoded({ extended: true })); // get information from html forms

  2. 如果设置了正文解析器,请尝试将标题更改为“multipart/form-data”或“text/plain”。

  3. 只是为了检查 req.query

干杯! :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM