简体   繁体   English

将数据保存到 a.json

[英]Saving data to a .json

I need to store data from a html form to.json file, but instead i'm getting this:我需要将 html 表单中的数据存储到 .json 文件,但我得到的是:

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

Javascript code for this: 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);
};

It's impossible to say without seeing your code, but my guess based on your question is that your html <form> doesn't have method="post" , so it's submitting as a GET.没有看到你的代码就不可能说,但我根据你的问题猜测是你的 html <form>没有method="post" ,所以它作为 GET 提交。 That would account for why you're seeing the params in the URL query string, and why your handler—which appears to be set up for POST requests—isn't doing what you expect, because that handler isn't receiving this request.这可以解释为什么您会在 URL 查询字符串中看到参数,以及为什么您的处理程序(似乎是为 POST 请求设置的)没有按照您的预期执行,因为该处理程序没有收到此请求。

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

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