【问题标题】:Error: GET 404 Page not found with Nuxtjs3错误:使用 Nuxtjs3 找不到 GET 404 页面
【发布时间】:2023-01-29 23:27:42
【问题描述】:

我正在学习 nuxtjs3。我正在尝试使用 fetch 在模板中获取数据。我正在学习某个教程,但不幸的是我被卡住了。我在应用程序和 mysql 本地数据库中使用 mysql2 library。但我收到错误:GET http://localhost:3000/api/users/index 404(找不到页面:/api/users/index)在控制台中。我究竟做错了什么。

下面是database.ts文件

import mysql from 'mysql2/promise'

const db = await mysql.createConnection({
    host: 'localhost',
    user: 'myuser',
    password: 'mypass',
    database: "mydb"
})

export default db

下面是 index.ts 文件

 import type { IncomingMessage, ServerResponse } from 'http'
 import db from '~~/server/middleware/database'

 export default async (req: IncomingMessage, res:ServerResponse) => { 
 const [rows,fields] = await db.execute("SELECT * FROM clients")
 return{
     staus: res.statusCode,
     columns: fields.map((i: any) => i.name),
     entries: rows,
     message: res.statusMessage
 }
}

下面是我要显示数据的 index.vue 文件。

<script setup>

import { ref, onMounted } from 'vue'

const entries = ref([])
const setEntries = async () => {
     const response = await fetch('/api/users/index')
     const data = await response.json()
     if('entries' in data) {
        entries.value = data.entries
      }
}

onMounted(setEntries)

</script>

<template>
<table class="table table-bordered table-striped mt-3">
  <thead>
    <tr>
      <th>Client Phone</th>
      <th>Client Email</th>
      
      <th style="width: 130px;">Action</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="user in entries" :key="user.client_phone">
      <td>{{ user.client_phone }}</td>
      <td>{{ user.client_email }}</td>
    </tr>
  </tbody>
</table>
</div>
</template>

以下是应用程序文件和文件夹的排列。

得到什么做错了错误:GET 404(找不到页面:/api/users/index)

【问题讨论】:

    标签: vuejs3 fetch-api nuxtjs3


    【解决方案1】:

    由于没有其他人回应,尽管我自己没有尝试过 nuxt fetch API,但我从阅读 Nitro Server Engine 文档中得出的最佳猜测是你应该使用 $fetch 而不是 fetch


    fetch 是本机 javascript fetch API,因此不会对您调用的应用程序和 API 端点有任何归属。

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


    $fetch 是一个用于 fetch 的 nuxt 包装器,我假设将注入一个 baseURL 和各种标头以使其工作。

    https://nuxt.com/docs/api/utils/dollarfetch#fetch

    const response = await $fetch('/api/users/index')
    

    我可以看到的下一个问题是根据server directory文档是server/api/users/index.ts中的导出应该使用defineEventHandler

    import db from '~~/server/middleware/database'
    
    export default defineEventHandler(async (event) => {
      const [rows,fields] = await db.execute("SELECT * FROM clients")
    
      return {
        staus: res.statusCode,
        columns: fields.map((i: any) => i.name),
        entries: rows,
        message: res.statusMessage
      }
    })
    

    【讨论】:

    • 我尝试将 fetch() 更改为 $fetch() 但仍然得到相同的响应 404 未找到页面。谢谢@Marc。
    • @GabrielRogath 我添加了一些我找到的更多信息。
    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2012-12-29
    • 2013-12-04
    • 2016-12-06
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多