gpt4 book ai didi

node.js - 从我的数据库中提取数据并将其(ById)填充到我的 Vue View (使用 Axios)时遇到问题。后端是 Node/Express

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:51 25 4
gpt4 key购买 nike

我通过控制台知道路由将其指向正确的 ID 号,但它抛出了 404,并且我不确定哪里的连接出现问题。

PrizesById 本质上是另一个保存名为 Prizes 的数据的路由的副本。我不确定重新创建两个单独的位置来提取相同的数据是否是一种方法,因为我找不到一种方法来获得奖品。两者的要求相同。

这是我的prizesbyid.js 的示例(在 route ):

  const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
res.send({
"prizesbyid": [{
id: 1,
name: "Cordoba C5",
description: "The Cordoba C5 Classical Guitar is perfect for any aspiring classical guitarist or steel-string/electric wizard looking to take a walk on the wild nylon-string side. The solid cedar top produces amazingly rich tone while the wide string placement, easy string tension, and low action make it a breeze to play.",
image_url: "../assets/c5Cor.jpg",
quantity: 5
},
{
id: 2,
name: "Merano MC400 Cello",
description: "Established in 2000, Merano have made it their mission to create affordable, beautifully crafted instruments. They offer brass, wind and stringed instruments all at reasonable prices. They have a large team of artisans who look over every instrument to ensure it maintains high standards. Many of their instruments are aimed at the beginner market but they also offer some fine examples of professional equipment as well.",
image_url: "",
quantity: 3
},
{
id: 3,
name: "Guarnerius del Gesu",
description: "A repreduction of the most expensive violin in the world, selling for an estimated $16million. The owner of the original anonymously donated the historic instrument to violinist Anne Akiko Meyers, on loan for the rest of her life.",
image_url: "",
quantity: 7
}
]
})
})

module.exports = router;

我通过我的 app.js 要求它,如下所示:

const prizesByIdRouter = require('./routes/prizesbyid');
app.use('/prizesbyid', prizesByIdRouter);

而前端axios调用是:

getPrizeById () {
axios.get('http://localhost:3000/prizebyid/' + this.prizeId).then(response => {
this.prize = response.data.prize
})
}

最佳答案

如果将所有内容重命名为 /prizes 路由,实际上会更容易。在您的prizes.js route :

const express = require('express');
const router = express.Router();

const prizes = [...]; // Extracted all data outside of the routes

router.get("/:id?", (req, res) => {
if (req.params.id !== undefined) {
// Send one by id
const result = prizes.find(prize => prize.id === +req.params.id);
res.status(200).send(result);
} else {
// Send all
res.status(200).send(prizes);
}
});

module.exports = router;

在你的 app.js 中:

const prizesRouter = require('./routes/prizes');
app.use('/prizes', prizesRouter);

该路由允许使用可选的 ID 参数。如果通过,路由将在数据中查找 ID 并发送回适当的结果。如果没有传递ID,则路由将传回所有数据。

关于node.js - 从我的数据库中提取数据并将其(ById)填充到我的 Vue View (使用 Axios)时遇到问题。后端是 Node/Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60385684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com