nuxt.js+express后端api接口配置與實現(xiàn)方式

Nuxt.js 是一個基于 Vue.js 的輕量級應(yīng)用框架,可用來創(chuàng)建服務(wù)端渲染 (SSR) 應(yīng)用。本文帶你了解在 Nuxt.js 中使用 Express 如何編寫實現(xiàn)后端的 api 接口。

創(chuàng)建接口文件

在項目根目錄中新建 server 文件夾并在該文件夾下創(chuàng)建一個 index.js 文件。

server
└── index.js

然后,在 server/index.js 中使用 Express 創(chuàng)建服務(wù)器路由中間件,以下創(chuàng)建一個返回字符串 ‘Hello World!’ 的簡單接口示例。

const app = require('express')();

app.get('/hello', (req, res) => {
  res.send('Hello World!')
})

module.exports = {
  path: 'api',
  handler: app
}

接下來,修改 nuxt.config.js 文件,在 serverMiddleware 配置項中添加 api 中間件。

module.exports = {
  serverMiddleware: [
    // API middleware
    '~/server/index.js'
  ],
}

現(xiàn)在,重啟服務(wù):

npm run dev

啟動后,在瀏覽器地址欄中輸入 http://localhost:3000/api/hello 查看是否成功返回 ‘Hello World!’。

對于如何注冊第三方路由的詳細(xì)用法請查看 nuxt.config.js 配置文檔serverMiddleware屬性的介紹。

在頁面中請求 api 數(shù)據(jù)

Nuxt.js添加了一種 asyncData 方法,可讓您在初始化組件之前處理異步操作。asyncData 每次在加載頁面組件之前都會調(diào)用。此方法將上下文作為第一個參數(shù),您可以使用它來獲取一些數(shù)據(jù),Nuxt.js 會將其與組件數(shù)據(jù)合并。

修改 api/hello 接口,使之返回 JSON 數(shù)據(jù)。

app.get('/hello', (req, res) => {
  res.json({
    title: 'Hello World!'
  })
})

在 pages/index.vue 中請求上面修改完成的 api/hello 接口。

export default {
  asyncData () {
    return fetch('http://localhost:3000/api/hello', { method: 'GET' })
      .then(res => res.json())
      .then(res => {
        // asyncData 方法獲取的數(shù)據(jù)會與組件數(shù)據(jù)合并,所以這里返回對象
        return {
          title: res.title
        }
      })
  }
}

如果需要請求多個接口,可如下示例:

<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>

接下來只需在 template 中綁定 title 即可顯示請求返回的數(shù)據(jù)。

<template>
  <h1>{{ title }}<h1>
</template>

關(guān)于異步獲取數(shù)據(jù)請移步文檔asyncData的介紹。
文章出處:Nuxt+Express后端api接口配置與實現(xiàn)方式

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

相關(guān)閱讀更多精彩內(nèi)容

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