【发布时间】: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)
【问题讨论】: