NodeJS Postman post request可以工作,但是afterpost不能,已经反复检查了客户端js

mkh04yzy  于 2023-11-17  发布在  Node.js
关注(0)|答案(1)|浏览(109)

我的问题是我有一个端点来创建一个项目,当我用Postman发送POST请求时,它可以工作。我使用node和express:

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发送并且请求体记录了正确的值时,该端点可以工作。
但是当我发送我的apache请求时,我的服务器代码将req.body记录为空对象('{}')。因为Postman工作,我相信问题出在我的客户端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();

a14dhokn

a14dhokn1#

我会怎么做:
1.将头部“application/json”更改为“application/x-www-form-urlencoded”,因为official docs没有关于前一个的信息。
1.停止使用$. aQuery并适应XHR请求,因为当CDN get滞后时,来自CDN的jquery有时会一团糟,而XHR是本机实现并立即可用。是的,这是代码混乱,但你总是知道这不是内部库逻辑的问题,而是你自己的问题。你盲目使用库,它将XHR隐藏在里面,您不知道如何提出正确的问题“XHR post method docs”,因为您还不熟悉下面的基本技术。
保存这个并导入变量

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中是否设置了body解析器
第一个月
1.如果设置了正文解析器,请尝试将标题更改为“multipart/form-data”或“text/plain”。
1.仅为了检查请求查询

相关问题