我正在使用this开始建立我的博客。
默认情况下,您将访问文章页面:http://localhost:3000/article?id=1
,我也希望这样:http://localhost:3000/article? slug=myslug
.
我的文章 Controller 如下:
module.exports = {
async findOne(ctx) {
//check if the params id is an id or a slug
const { id } = ctx.params;
// if you use MongoDB database
// we are validating that the id match ObjectID format
if (id.match(/^[0-9a-fA-F]{24}$/)) {
const entity = await strapi.services.article.findOne(ctx.params);
return sanitizeEntity(entity, { model: strapi.models.article });
}
// findOne function works only with IDs
// so we find all and get first entry by using slug
const [entity] = await strapi.services.article.find({ slug: id });
return sanitizeEntity(entity, { model: strapi.models.article });
}
};
文章配置路由是:
...
{
"method": "GET",
"path": "/articles/:id",
"handler": "article.findOne",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/articles/:slug",
"handler": "article.findOne",
"config": {
"policies": []
}
},
...
如果我这样做 http://localhost:1337/articles?id=1
或 http://localhost:1337/articles?slug=this-is-my-title
我按预期返回了内容。
但是,当我点击http://localhost:3000/article?slug=this-is-my-title
我得到以下信息:
在页面文件夹中(使用 Next.js 构建的前端)我有 pages/article
:
const Article = () => {
const router = useRouter();
const { data, loading, error } = useQuery(ARTICLE_QUERY, {
variables: { slug: router.query.slug }
});
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {JSON.stringify(error)}</p>;
return (
<Layout>
{console.log(data)}
</Layout>
);
};
ARTICLE_QUERY
是:
const ARTICLE_QUERY = gql`
query Articles($slug: String!) {
article(slug: $slug) {
id
title
content
image {
url
}
category {
id
name
}
published_at
}
}
`;
是否需要进一步配置来解决此问题?
最佳答案
错误来自更严格的类型检查
article
查询需要一个 ID!
参数,提供 slug
(字符串)无法满足此要求。
您需要提供单独的查询(和解析器),例如articleBySlug
来匹配url字符串类型参数。
您还需要检查某些父组件中的 url 参数类型以使用正确的查询(呈现不同的子组件)。
关于javascript - GraphQl查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61174336/