首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正在尝试导入JSON文件,以便在程序运行后立即发布到API上

正在尝试导入JSON文件,以便在程序运行后立即发布到API上
EN

Stack Overflow用户
提问于 2021-03-13 23:41:12
回答 1查看 22关注 0票数 0

我正在构建一个外卖网络应用程序,其中我需要在我的服务器上的一些项目。我想在服务器一运行就将所有这些JSON数据导入到服务器上。然后使用axios获取它并在我的购物车组件中更新它。多么。我是否要导入JSON文件并确保所有项都放入我自己的API中

JSON文件:

代码语言:javascript
复制
[
{
    "id": 1,
    "name": "small burger",
    "price": 3.00
},
{
    "id": 2,
    "name": "medium burger",
    "price": 4.20

},
{
    "id": 3,
    "name": "large burger",
    "price": 5.00
},
{
    "id": 4,
    "name":"medium drink",
    "price": 1.50
},
{
    "id": 5,
    "name":"large drink",
    "price": 2.00
},
{
    "id": 6,
    "name":"xl drink",
    "price": 2.50
},
{
    "id": 7,
    "name":"small fries",
    "price": 2.00
},
{
    "id": 8,
    "name":"medium fries",
    "price": 3.00
},
{
    "id": 9,
    "name":"large fries",
    "price": 4.00
}

]

服务器/INDEX.JS

代码语言:javascript
复制
const app = express()
const bc = require('./controllers/foodCtrl')

const port = 4000

app.use(express.json())

app.get('/api/foods', bc.read)
app.post('/api/foods-in-cart', bc.create)
app.put('/api/foods-in-cart/:id', bc.update)
app.delete('/api/foods-in-cart/:id', bc.delete)

app.listen(port, () => console.log('Server running on ' + port))






SERVER/CONTROLLERS/foodCtrl.js

    // import * as foods from '.../food.json'
const food = []
let id = 1

module.exports = {

    read: (req, res) => {
        res.status(200).send(food)
    },
    
    create: (req, res) => {

        food.push(
            {
                id: id,
                name: req.body.name,
                price: req.body.price
            }
        )
        id++
        res.status(200).send(food)
    },

    update: (req, res) => {
        const {id} = req.params
        let foodIndex = 0
        food.map((element, index) => {
            if(element.id === +id){
                foodIndex = index
            }
        })
        let updateName = {
            id: +id,
            name: req.body.name,
            price: req.body.price
        }
        food.splice(foodIndex, 1, updateName)
        res.status(200).send(food)
    },
    delete: (req, res) => {
        const {id} = req.params
        let index2 = 0

        food.map((element, i) => {
            if(element.id === +id){
                index2 = i
            }
        })

        food.splice(index2, 1)
        res.status(200).send(food)
    }



}
EN

回答 1

Stack Overflow用户

发布于 2021-03-14 00:13:54

这非常简单,您只需在SERVER/CONTROLLERS/foodCtrl.js上添加const food = require('./food.json');即可。

JSON将被加载并解析为Javascript对象,您可以通过food访问它

你可能会问,为什么我们可以直接导入JSON文件?这是因为node提供了开箱即用的功能。

你可以在https://nodejs.org/api/modules.html#modules_all_together上阅读更多

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66615347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档