首页 > 解决方案 > 如何从对象更改我的请求有效负载以从表单中显示我的内容?

问题描述

当我打开本地网络浏览器时,我可以看到“请求有效负载”只是向我展示了一个包含两个对象的数组,例如 [object Object]。

我该如何解决这个问题,以便“请求有效负载”将向我显示内容?

前任:{name: "Kevin", content: "pew pew"}


const form = document.querySelector("form");
const loadingElement = document.querySelector(".loading");
const API_URl = "http://localhost:5000/holla";

loadingElement.style.display = "none";

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const formData = new FormData(form);
  const name = formData.get("name");
  const content = formData.get("content");

  const holla = {
    name,
    content,
  };

  form.style.display = "none";
  loadingElement.style.display = "";

  fetch(API_URl, {
    method: "POST",
    body: holla,
    headers: {
      headers: {
        "content-type": "application/json",
      },
    },
  });
});


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

const app = express();

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

app.get("/", (req, res) => {
  res.json({
    message: "Hollered at! what you gonna do about it!",
  });
});

app.post("/holla", (req, res) => {
  console.log(req.body);
});

app.listen(5000, () => {
  console.log("listening on http://locahost:5000");
});

标签: javascriptnode.jsexpress

解决方案


尝试使用:

body: JSON.stringify(holla),

发送对象的 JSON 字符串表示


推荐阅读