Next.js與TypeScript從零起步學(xué)習(xí)筆記-4.獲取數(shù)據(jù)以及API路由

接上節(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

開(kāi)啟瀏覽器,我們可以看到一個(gè)application/json格式的一個(gè)api接口,如圖5:
圖5.png

git地址:https://github.com/JaqenHo/next_js_learn.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容