1

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

PrizesById本质上是另一个保存数据的路由的副本,称为Prizes. 我不确定重新创建两个单独的位置来提取相同的数据是否是一种方法,因为我找不到为prizes. 两者都需要相同的方式。

这是我的 Prizesbyid.js 示例(在路线中):

  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
  })
}
4

1 回答 1

0

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

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,则路由将传回所有数据。

于 2020-02-25T00:31:20.787 回答