【发布时间】:2020-07-25 05:05:21
【问题描述】:
我正在使用this starter 来构建我的博客。
默认情况下,您将访问文章页面:http://localhost:3000/article?id=1,我也希望:http://localhost:3000/article?slug=myslug。
我的文章控制器如下:
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
我得到以下信息:
在 pages 文件夹内(使用 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
}
}
`;
是否需要任何进一步的配置来解决这个问题?
【问题讨论】:
标签: javascript reactjs graphql next.js strapi