王朝阳 發表於 2020-6-17 13:39:00

初步学习next.js-4-在getInitialProps中用axios获取数据

<div class="cnblogs_code">
<pre>yarn add axios</pre>
</div>
<div class="cnblogs_code">
<pre>import axios from 'axios'</pre>
</div>
<div class="cnblogs_code">
<pre>const Page = ({ stars }) =&gt;
&lt;div&gt;<span style="color: rgba(0, 0, 0, 1)">
    Next stars: {stars}
</span>&lt;/div&gt;
<span style="color: rgba(0, 0, 0, 1)">
Page.getInitialProps </span>= async ({ req }) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
const res </span>= await fetch('https://api.github.com/repos/zeit/next.js'<span style="color: rgba(0, 0, 0, 1)">)
const json </span>=<span style="color: rgba(0, 0, 0, 1)"> await res.json()
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> { stars: json.stargazers_count }
}

export </span><span style="color: rgba(0, 0, 255, 1)">default</span> Page</pre>
</div>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/lxz-blogs/p/13151996.html
頁: [1]
查看完整版本: 初步学习next.js-4-在getInitialProps中用axios获取数据