使用提取将跨域JSON数据发布到Express后端

时间:2018-09-14 05:15:30

标签: 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 Server

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

1 个答案:

答案 0 :(得分:2)

您不能POST使用普通的javascript对象。

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

根据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));
});