node.js - 使用 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 文件中。
解决方案
您需要 app.js 文件中的整个 allrecipes 文件。您只需要从 allrecipes.json 文件中获取 recipes 数组。因此,在要求时,请执行以下操作
let recipes=require('./allrecipes').recipes
推荐阅读
- compiler-errors - windows Defender 修改了 Microsoft.CppCommon.targets
- jquery - 来自 SquareSpace 表单的 jQuery Ajax 调用
- python - 非严格不等式作为 Python 库 cvxpy 中的约束
- directx - 无法设置 TextureWic C++DirectX
- mysql - 如何使用 ST_contains 从 MySQL 8 中的表中进行选择?
- javascript - 如何删除以前的
在显示另一个之后
?
- sublimetext2 - Sublime Text 2 - 包控制错误
- spring - 从 springboot 2.0.2 迁移到 2.2.2 时出现 JSON 解散问题
- python - Python - 使用文件引导程序 SuperCollider
- javascript - 将 socket.io 封装在一个类中