我正在构建一个外卖网络应用程序,其中我需要在我的服务器上的一些项目。我想在服务器一运行就将所有这些JSON数据导入到服务器上。然后使用axios获取它并在我的购物车组件中更新它。多么。我是否要导入JSON文件并确保所有项都放入我自己的API中
JSON文件:
[
{
"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
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)
}
}发布于 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上阅读更多
https://stackoverflow.com/questions/66615347
复制相似问题