首页 > 解决方案 > 使用 Express 的 fetch() POST 请求:JSON 输入意外结束

问题描述

我一直在尝试使用一些 HTTP 请求进行练习,特别是我想发送一个 POST 请求,其中数据取自一个字段,并通过 fetch() 发送到我的本地主机上的一个 url,该 url 设置为 express。从那里我想以某种方式获取响应并将其显示在我的 HTML 文档中。

但是,在将 response.json() 设置为未定义以外的任何内容时,我遇到了一个真正的难题。

这是我的前端脚本:

const url = "/result";

const inputField = document.querySelector("#write");
const submitButton = document.querySelector("#submit");
const responseField = document.querySelector("#text-goes-here");

const postText = async () => {
  const text = inputField.value;
  const data = JSON.stringify({ destination: text });

  try {
    const response = await fetch(url, {
      method: "POST",
      body: data,
      headers: {
        "Content-type": "application/json",
      },
    });

    if (response.ok === true) {
      const jsonResponse = await response.json();
      responseField.innerHTML = jsonResponse;
    }
  } catch (error) {
    console.log(error);
  }
};

const displayText = (event) => {
  event.preventDefault();

  while (responseField.firstChild) {
    responseField.removeChild(responseField.firstChild);
  }

  postText();
};

submitButton.addEventListener("click", displayText);

和我的服务器脚本:

const express = require("express");
const bodyParser = require("body-parser");
const read = require('fs');
const router = express.Router();
const app = express();

const port = 3000;


app.use(express.static(__dirname + "/public"));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.get("/", (req, res) => {
    res.sendFile("public/index.html");
})

router.post("/result", (req, res) => {
    console.log(req.body);
    res.send();
});

app.use("/", router);

app.listen(port, () => {
    console.log(`Server running at port: ${port}`)
});

我在开发控制台中进行了一些挖掘,发现 (response.ok) 实际上是“真”,但它在 catch 语句中出错,说“SyntaxError:在 postText (script.js:23) 处 JSON 输入意外结束”

这正是这一行:

const jsonResponse = await response.json();

谁能阐明我在这里做错了什么?在这一点上我不知所措

标签: javascriptexpresspostfetch

解决方案


此错误意味着您正在尝试解析不是有效 JSON 对象的内容。

"SyntaxError: Unexpected end of JSON input at postText (script.js:23)"

这是真的,因为您发送回前端的响应不是 JSON。

router.post("/result", (req, res) => {
    console.log(req.body);
    // The response is not a valid JSON object
    res.send();
});

您可以更改res.send()res.json()并给它一个有效的对象。

res.json({ name:"John", age:30, car:null })

推荐阅读