首页 > 解决方案 > 如何使用 JavaScript 将表单数据发送到服务器

问题描述

我正在使用两台服务器,一台用于React(在 address 上http://localhost:3000/contact),另一台用于Express(在 address 上http://localhost:5000/)。我想通过一些 HTTP 请求方法作为 POST 方法发送表单数据对象,但我在“后端”端得到空对象。

我有一个带有onSubmit事件的简单表单,它首先使用表单数据值创建一个对象:

const data = {
    firstInput: evt.target.elements.firstInput.value,
    secondInput: evt.target.elements.secondInput.value
}

注意:我使用 DevTools 和 React Dev 工具测试了 If get all data until here,直到这里它工作得很好。

第二个使用 Express 的服务器只有一个简单的端点,它应该接收这些数据或至少打印我在req.body对象中发送的内容:

server.post("/", (req, res) => {
    res.end(req.body);
});

注意 2:还测试了这个端点,它工作正常,但req.body得到一个空对象。

我已经测试了几种方法,例如:

原生fetchAPI:

fetch("http://localhost:5000/", {
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
    }).then(res => {
        console.log(res);
    });

错误

错误

此外,尝试使用async/await方法,fetch API但我不确定是否在 React 组件上使用它。

我也尝试过http API,但我得到了相同的结果。

我想我的第一个问题是如何将格式正确的数据从组件端发送到服务器端。不管怎么说,还是要谢谢你。

标签: javascriptnode.jsreactjsexpressfetch-api

解决方案


使用这个包查询字符串 你可以像这样使用:

import queryString from 'query-string';
fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important
    body: queryString.stringify({for:'bar', blah:1}
});

推荐阅读