P15:前中台结合2-文章详细页面接口制作展示
目录
首页的接口和展示已经差不多了,现在可以制作详细页的接口和内容。这节课主要目的是制作文章详细页面的接口,通过一个 ID 查找出详细的信息。
编写中台详细页面接口
先打开/service/app/controller/default/home.js
文件,编写接口,代码如下。需要注意的是整个接口是需要接收文章 ID,然后根据文章 ID 查出内容的。
home.js 文件
async getArticleById() { // 先配置路由的动态传值,然后再接收值 const id = this.ctx.params.id; const sql = 'SELECT article.id as id,' + 'article.title as title,' + 'article.introduce as introduce,' + 'article.article_content as article_content,' + "FROM_UNIXTIME(article.addTime,'%Y-%m-%d %H:%i:%s' ) as addTime," + 'article.view_count as view_count ,' + 'type.typeName as typeName ,' + 'type.id as typeId ' + 'FROM article LEFT JOIN type ON article.type_id = type.Id ' + 'WHERE article.id=' + id; const result = await this.app.mysql.query(sql); this.ctx.body = { data: result }; }
编写完成后,这个接口就可以使用了,但是不要忘记,开启 MySql 服务和中台接口服务。
编写前台链接导航
有了接口,先不着急编写详细页面,先把首页到详细页的链接做好。这个直接使用 Next.js 中的<Link>
标签就可以了。找到首页中循环时文章的标题,在外边包括<Link>
标签就可以了。
需要注意的是,这里
此段代码在/blog/pages/index.js
<div className="list-title"> <Link href={{pathname:'/detailed',query:{id:item.id}}}> <a>{item.title}</a> </Link> </div>
详细页从接口获取数据
当我们能通过链接跳转到详细页面之后,就可以编写detailed.js
,通过getInitialProps
来访问中台接口,并从中台接口获得数据。
先配置一下 router 路由,打开service/app/router/default.js
router.get('/default/getArticleById/:id', controller.default.home.getArticleById);
pages/detailed.js
文件中的代码
Detailed.getInitialProps = async(context) => { let id = context.query.id; const promise = new Promise((resolve)=>{ axios('http://127.0.0.1:7001/default/getArticleById/' + id).then((res) => { resolve(res.data.data[0]) }) }) return await promise }
写完之后我们访问一下代码,看看是不是可以拿到后台的数据(后台数据你可以尽量多准备一些)。如果预览可以拿到数据,证明我们的编写是没有问题的。但是当你点击标题访问文章详情页时控制台会报如下错误,即跨域问题。
本文就到这里,下节我们将解决 egg.js 的跨域问题
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » P15:前中台结合2-文章详细页面接口制作展示
码云笔记 » P15:前中台结合2-文章详细页面接口制作展示