Api调用无法识别查询参数



我这里有一个后端路由器,它从postgress数据库中获取书籍数据。我正在尝试连接一个路由器,它可以提取并返回特定类型的书籍。我目前正在尝试从url中提取书籍数据,console.log似乎以适当的格式返回了适当的单词。此api调用在以下情况下有效:

  1. 流派是硬编码的
  2. 该流派在->quot;'这种格式"<--单引号和双引号

{
"id": 1,
"title": "The Hunger Games",
"series": "The Hunger Games #1",
"author": "Suzanne Collins",
"description": "WINNING MEANS FAME AND FORTUNE.LOSING MEANS CERTAIN DEATH.THE HUNGER GAMES HAVE BEGUN. . . .In the ruins of a place once known as North America lies the nation of Panem, a shining Capitol surrounded by twelve outlying districts. The Capitol is harsh and cruel and keeps the districts in line by forcing them all to send one boy and once girl between the ages of twelve and eighteen to participate in the annual Hunger Games, a fight to the death on live TV.Sixteen-year-old Katniss Everdeen regards it as a death sentence when she steps forward to take her sister's place in the Games. But Katniss has been close to dead before—and survival, for her, is second nature. Without really meaning to, she becomes a contender. But if she is to win, she will have to start making choices that weight survival against humanity and life against love.",
"language": "English",
"isbn": "9780439023481",
"genres": [
"'Young Adult'",
"'Fiction'",
"'Dystopia'",
"'Fantasy'",
"'Science Fiction'",
"'Romance'",
"'Adventure'",
"'Teen'",
"'Post Apocalyptic'",
"'Action'"
],
"bookformat": "Hardcover",
"pages": 374,
"publisher": "Scholastic Press",
"coverimg": "https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1586722975l/2767052.jpg",
"price": 509,
"bought": false,
"createdAt": null,
"updatedAt": null
},

const router = require("express").Router();
const {
models: { Book },
} = require("../db");
//const { Op } = require('@sequelize/core');
const { Op } = require('Sequelize')
module.exports = router;
router.get('/:genre', async(req, res, next) => {
try{
const genre = req.params.genre;
const genreBook = await Book.findAll({
where: {
genres:{
[Op.contains]: ["'Fiction'"]
}
}
});
console.log('The genre url', typeof genre)
console.log('stringified genre', typeof String(genre))
res.json(genreBook)
}catch(e){
next(e)
}
})

这里插入的是一本JSON格式的书,它被返回和路由器。请帮助

这里有两个选项。。。

  1. 当您提出请求时,将引号编码到路由参数中,例如

    const genre = "'Fiction'"
    fetch(`https://example.com/${encodeURIComponent(genre)}`)
    

    这将向https://example.com/'Fiction'发出请求,看起来非常糟糕的IMO

  2. 在查询中使用genre路由参数时,用引号将其括起来

    Book.findAll({
    where: {
    [Op.contains]: [`'${genre}'`]
    }
    })
    

    您对此的请求URL看起来像https://example.com/Fiction

最新更新