【发布时间】:2020-04-15 04:14:00
【问题描述】:
我有这个当前的服务器代码:
const express = require("express")
const fs = require("fs")
const router = express.Router()
const path = require("path")
const todos = JSON.parse(fs.readFileSync(path.join(__dirname, "../db", "todolist.json"), "utf8"))
router.get("/", async (req, res) => {
res.send(todos)
})
router.post("/new", async (req, res) => {
const { title, description } = req.body
const todoItem = {
id: "3",
title,
description
}
todos.todos.push(todoItem)
const data = JSON.stringify(todos, null, 2)
fs.writeFile(path.join(__dirname, "../db", "todolist.json"), data, () => {})
res.status(201).json(todoItem)
})
客户:
console.log("Hello world!")
const somedata = {
title: "A new boy",
description: "Recieved from the client"
}
const main = async () => {
const response1 = await fetch("http://localhost:3000/todo", {
method: "GET",
})
const data1 = await response1.json()
const response2 = await fetch("http://localhost:3000/todo/new", {
method: "POST",
body: JSON.stringify(somedata),
headers: {
'Content-Type': 'application/json',
"Accept": "application/json"
}
})
const data2 = await response2.json()
return { data1, data2 }
}
main().then(data => console.log(data))
当我发出 /POST 请求以创建新实体时,浏览器只会一遍又一遍地循环请求,直到我必须手动退出服务器。如果我出于某种原因使用邮递员,则不会发生这种情况。是否有人在这里看到有关 writeFile 方法的使用方式以及为什么它不断重新加载浏览器以继续推送 POST 请求的任何明显错误?
谢谢! :)
【问题讨论】:
-
您发布的服务器代码中是否缺少某些内容?它只显示
/获取路线和/todo发布路线。但是,客户端代码显示了一个到 /todo 的 GET 和一个到 /todo/new 的 POST? -
我正在使用快速路由器功能,在 server.js 中(此处不包含),您可以像这样指定路由,但这不是问题的一部分。
标签: node.js google-chrome express fs