javascript - 使用 fetch 将跨域 JSON 数据发布到 Express 后端

标签 javascript node.js express post fetch

我正在尝试使用 Fetch 从表单中发布一些 JSON 数据并记录来自 Express 服务器的响应,这应该是一个包含发布的表单值的简单 JSON 响应,但我只收到一个空对象控制台。

可以从此 JSFiddle Link 执行 HTML 和 JavaScript .

如何从服务器接收填充的 JSON 对象响应?

HTML

<form id="myForm">
    <input type="text" placeholder="Enter First Name" name="firstName" />
    <input type="text" placeholder="Enter Last Name" name="lastName" />
    <input type="submit" value="SUBMIT" />
</form>

JavaScript

const form = document.getElementById("myForm");

form.addEventListener("submit", (e) => {

    e.preventDefault();

    fetch("http://localhost:5000/form-post", {
            method: "POST",
            mode: "cors",
            body: {
                firstName: e.target.firstName.value,
                lastName: e.target.lastName.value
            } 
        })
        .then((res) => res.json())
        .then((data) => console.log(data));
});

Express 服务器

const express = require("express");
const app = express();

const cors = (req, res, next) => {

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
    res.header("Access-Control-Allow-Headers", "Origin, Content-Type");

    next();
};

app.use(cors);
app.use(express.json());

app.post("/form-post", (req, res) => {

    res
        .status(200)
        .json({
            First_Name: req.body.firstName,
            Last_Name: req.body.lastName
        });

});

app.listen(5000, () => console.log("Server started on port 5000..."));

[编辑:] 它在 Postman 中工作正常(附有屏幕截图),但似乎不适用于 Fetch。

enter image description here

最佳答案

您无法POST纯 JavaScript 对象。

但是,请检查RFC 1341中定义的Content-type的所有可能值。列表为mime types .

根据MDN

Fetch body data type must match "Content-Type" header.

请尝试使用此代码。

const form = document.getElementById("myForm");

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

  var data = {
    firstName: e.target.firstName.value,
    lastName: e.target.lastName.value
  }

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

关于javascript - 使用 fetch 将跨域 JSON 数据发布到 Express 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52325363/

相关文章:

javascript - React JS - 在数组末尾停止无限滚动

node.js - 使用phoenix_api_docs

javascript - Express 中的分隔路线

node.js - 错误:property 'token' does not exist on type' () => any'

node.js - 使用 express 和 body-parser 解析 DELETE 请求时 body 为空

javascript - 如何仅为 POST 请求创建 Node 服务器

javascript - 如何在 HighCharts 中单击另一个系列面积图下方的系列面积图?

javascript - JQuery-ui,自动隐藏对话框

javascript - 数组中的字符串显示为未定义,尽管在几行之前已成功进行 console.log-ed

node.js - express-Formidable "Can' t 在发送后设置 header 。”