接上節(jié)內(nèi)容,此文章,會(huì)介紹獲取數(shù)據(jù)以及API路由
參考官網(wǎng):https://nextjs.org/learn/basics/getting-started
git上面有大量TypeScript的例子,很多時(shí)間從推:https://github.com/zeit/next.js/tree/canary/examples
開(kāi)發(fā)環(huán)境:
window10 x64
node v10.16.3
npm v6.13.4
1.獲取數(shù)據(jù)
在我們實(shí)際開(kāi)發(fā)中,數(shù)據(jù)大多數(shù)來(lái)源自接口,我們將引入‘isomorphic-unfetch’這library,里面會(huì)提供一些方法以供我們獲取數(shù)據(jù),首先在命令行安裝‘isomorphic-unfetch’,敲入:
npm install isomorphic-unfetch
等它安裝完,如圖1:
圖1.png
安裝完之后,讓我們來(lái)創(chuàng)建一個(gè)新頁(yè)面,就叫'fetchData'吧!
創(chuàng)建'pages/fetchData.tsx',然后敲入如下代碼:
//pages/fetchData.tsx
import { NextPage,NextPageContext } from 'next';
import fetch from 'isomorphic-unfetch';
interface Show extends NextPageContext {
id: number;
name: string;
}
const FetchData: NextPage<{ shows: Array<Show> }> = (props) => (
<div>
<h1>Batman TV Shows</h1>
<ul>
{props.shows.map(show => (
<li key={show.id}>
id=>{show.id};
<br/>
name=>{show.name}
</li>
))}
</ul>
</div>
);
FetchData.getInitialProps = async (ctx: Show) => {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
const data = await res.json();
console.log(`Show data fetched. Count: ${data.length}`);
return {
shows: data.map((entry: any) => entry.show)
};
};
export default FetchData;
如圖2:

如圖2.png
其中https://api.tvmaze.com/search/shows?q=batman接口是官網(wǎng)提供的例子,找的關(guān)于蝙蝠俠的tv show。。
啟動(dòng)瀏覽器,url敲入http://localhost:3000/fetchData
可以看到效果,如圖3:

如圖3.png
2.API路由
我們能在此創(chuàng)建RESTful API,開(kāi)發(fā)放給外面用,這個(gè)只是簡(jiǎn)單的接口例子,真正你的接口,你可能還需要日志,權(quán)限驗(yàn)證等等。
我們?cè)?pages'下創(chuàng)建一個(gè)目錄,叫'api',然后在'api'創(chuàng)建一個(gè)文件,叫'randomQuote.ts',在文件里敲入如下代碼:
//pages/api/randomQuote.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default (req: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({
param:req.query.param,
quote: 'Write tests, not too many, mostly integration',
author: 'Kun'
});
};
如圖4:
如圖4.png

圖5.png