fs.writefile在我的快速应用程序中无限期地使POST请求循环

问题描述 投票:0回答:1

我有当前的服务器代码:

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请求以创建新实体时,浏览器会一遍又一遍地循环请求,直到我必须手动退出服务器为止。如果出于某种原因我使用邮递员,则不会发生这种情况。是否有人在这里看到任何明显的错误,如如何使用readFile方法以及为什么它不断重新加载浏览器以继续推送POST请求?

谢谢! :)

node.js google-chrome express fs
1个回答
0
投票

我认为您应该使用fs.writeFileSync()或在其回调中编写一些代码

© www.soinside.com 2019 - 2024. All rights reserved.