首页 > 解决方案 > 使用 json 文件发布请求

问题描述

我已经创建了一个 JSON 文件,并且我正在尝试执行一个发布请求以将更多数据添加到我的 JSON 文件中。我想通过使用 req.body 来做到这一点。下面是我的 JSON 文件和节点 js 代码。

  "recipes": [
{
   "recipe_id": "001",
   "food_recipe": "Fried Rice",
   "cook_time": 20,
   "ingridients": "white rice, eggs, mixed vegatable,hotsauce, soya sauce",
   "cooking_instructions": "https://therecipecritic.com/easy-fried-rice/"

}
]
}

上面的 allrecipes.json 文件

const express = require('express');
const app = express();
const fs = require('fs');
const bodyparser = require('body-parser');
const recipes = require('./allrecipes');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));

app.post('/recone',(req,res)  => {
     let addrecipe = {
       recipe_id: "2",
       food_recipe: "Chicken Paramsean",
       cook_time: 40,
       ingridients: "chiken,breading,flour,egg,red sauce,mozzarella",
       cooking_instructions: "https://www.allrecipes.com/recipe/223042/chicken-parmesan/"
     };

     recipes.push(addrecipe);

  fs.writeFile('allrecipes.json',JSON.stringify(recipes), err => {
      if (err) throw err;
        res.status(200).send('New recipe added');
  });

  });

以上是我的 app.js 文件。

出于测试目的,我对对象中的值进行了硬编码,但是当我运行它时,我收到一条错误消息,说 push 不是函数。我的最终结果是使用 JSON 正文将数据发布到我的 json 文件中。

标签: node.jsjson

解决方案


您需要 app.js 文件中的整个 allrecipes 文件。您只需要从 allrecipes.json 文件中获取 recipes 数组。因此,在要求时,请执行以下操作

let recipes=require('./allrecipes').recipes


推荐阅读