Nuxt.js 是一個(gè)基于 Vue.js 的輕量級(jí)應(yīng)用框架,可用來(lái)創(chuàng)建服務(wù)端渲染 (SSR) 應(yīng)用哮肚。本文帶你了解在 Nuxt.js 中使用 Express 如何編寫(xiě)實(shí)現(xiàn)后端的 api 接口鸭蛙。
創(chuàng)建接口文件
在項(xiàng)目根目錄中新建 server 文件夾并在該文件夾下創(chuàng)建一個(gè) index.js 文件。
server
└── index.js
然后,在 server/index.js 中使用 Express 創(chuàng)建服務(wù)器路由中間件骚灸,以下創(chuàng)建一個(gè)返回字符串 ‘Hello World!’ 的簡(jiǎn)單接口示例。
const app = require('express')();
app.get('/hello', (req, res) => {
res.send('Hello World!')
})
module.exports = {
path: 'api',
handler: app
}
接下來(lái),修改 nuxt.config.js 文件祟绊,在 serverMiddleware 配置項(xiàng)中添加 api 中間件。
module.exports = {
serverMiddleware: [
// API middleware
'~/server/index.js'
],
}
現(xiàn)在哥捕,重啟服務(wù):
npm run dev
啟動(dòng)后牧抽,在瀏覽器地址欄中輸入 http://localhost:3000/api/hello 查看是否成功返回 ‘Hello World!’。
對(duì)于如何注冊(cè)第三方路由的詳細(xì)用法請(qǐng)查看 nuxt.config.js 配置文檔serverMiddleware屬性的介紹遥赚。
在頁(yè)面中請(qǐng)求 api 數(shù)據(jù)
Nuxt.js添加了一種 asyncData 方法扬舒,可讓您在初始化組件之前處理異步操作。asyncData 每次在加載頁(yè)面組件之前都會(huì)調(diào)用凫佛。此方法將上下文作為第一個(gè)參數(shù)讲坎,您可以使用它來(lái)獲取一些數(shù)據(jù),Nuxt.js 會(huì)將其與組件數(shù)據(jù)合并愧薛。
修改 api/hello 接口晨炕,使之返回 JSON 數(shù)據(jù)。
app.get('/hello', (req, res) => {
res.json({
title: 'Hello World!'
})
})
在 pages/index.vue 中請(qǐng)求上面修改完成的 api/hello 接口毫炉。
export default {
asyncData () {
return fetch('http://localhost:3000/api/hello', { method: 'GET' })
.then(res => res.json())
.then(res => {
// asyncData 方法獲取的數(shù)據(jù)會(huì)與組件數(shù)據(jù)合并瓮栗,所以這里返回對(duì)象
return {
title: res.title
}
})
}
}
如果需要請(qǐng)求多個(gè)接口,可如下示例:
<template>
<div>
<h1>{{ title }}</h1>
<ul>
<li v-for="item in list" :key="item.id">{{ item.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
export default {
async asyncData () {
let res1 = await fetch('http://localhost:3000/api/hello', { method: 'GET' }).then(res => res.json());
let res2 = await fetch('http://localhost:3000/api/list', { method: 'GET' }).then(res => res.json());
console.log(res1,res2.data)
return {
title: res1.title,
list: res2.data
};
}
}
</script>
接下來(lái)只需在 template 中綁定 title 即可顯示請(qǐng)求返回的數(shù)據(jù)瞄勾。
<template>
<h1>{{ title }}<h1>
</template>
關(guān)于異步獲取數(shù)據(jù)請(qǐng)移步文檔asyncData的介紹费奸。
文章出處:Nuxt+Express后端api接口配置與實(shí)現(xiàn)方式