繁体   English   中英

将数据保存到 a.json

[英]Saving data to a .json

我需要将 html 表单中的数据存储到 .json 文件,但我得到的是:

http://localhost:3000/teachers/create?avatar_url=&name=&birth=&grade=medio&class_type=P&lesson=

Javascript 代码:

const fs = require("fs");
const data = require("./data.json");

exports.post = function (req, res) {
    const keys = Object.keys(req.body);

    for (key of keys) {
        if (req.body[key] == "") {
            return res.send("Please, fill in all fields!");
        }
    }

    let { avatar_url, birth, name, grade, class_type, lesson } = req.body;

    birth = Date.parse(birth);
    const created_at = Date.now();
    const id = Number(data.teachers.length + 1);

    data.teachers.push({
        id,
        name,
        avatar_url,
        birth,
        grade,
        class_type,
        lesson,
        created_at,
    });

    fs.writeFile("data.json", JSON.stringify(data, null, 2), function (err) {
        if (err) return res.send("Write file error!");

        return res.redirect("/teachers");
    });

    //return res.send(req.body);
};

没有看到你的代码就不可能说,但我根据你的问题猜测是你的 html <form>没有method="post" ,所以它作为 GET 提交。 这可以解释为什么您会在 URL 查询字符串中看到参数,以及为什么您的处理程序(似乎是为 POST 请求设置的)没有按照您的预期执行,因为该处理程序没有收到此请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM