【问题标题】:fetch() POST requests with Express: unexpected end of JSON inputfetch() 使用 Express 的 POST 请求:JSON 输入意外结束
【发布时间】:2021-03-13 08:33:09
【问题描述】:

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

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

这是我的前端脚本:

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:JSON 输入的意外结束 在 postText (script.js:23)"

正是这一行:

const jsonResponse = await response.json();

谁能解释我在这里做错了什么?我现在很茫然

【问题讨论】:

    标签: javascript express post fetch


    【解决方案1】:

    此错误表示您正在尝试解析不是有效 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 })
    

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2016-09-08
      • 2018-01-23
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2020-07-10
      • 2021-10-08
      相关资源
      最近更新 更多