首页 > 解决方案 > 获取发送 EMPTY 对象到 Node 服务器的 http POST 请求

问题描述

我正在尝试从 html 表单向我的节点服务器发出 HTTP Post 请求。我使用 Body Parser 和所有东西,但是当我尝试获取请求并将 req.body 记录在我的服务器中时,它是一个 EMPTY 对象。你知道我该如何解决这个问题吗?

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const form = document.querySelector('form');

form.addEventListener('submit', e => {
  e.preventDefault();

  const email = document.querySelector('#email').value;
  const password = document.querySelector('#password').value;
  const formData = { email, password };

  const options = {
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify(formData),
    mode: 'no-cors'
  };

  fetch('http://localhost:3000/users/login', options)
    .then(res => {
      console.log(res);
      res.json();
    })
    .then(data => {
      console.log(data);
    });

标签: javascripthtmlnode.jsexpressfetch

解决方案


您说过mode: 'no-cors',所有需要 CORS 权限的内容都将被忽略(包括将Content-Type标头设置为application/json)。

删除mode: 'no-cors'(并使用服务器上的cors 中间件)。


推荐阅读