前言
本文主要為大家介紹,如何使用 Next 框架實(shí)現(xiàn)一個(gè)簡(jiǎn)單的后端接口,并且從數(shù)據(jù)庫(kù)中請(qǐng)求數(shù)據(jù)返回給前端。
實(shí)現(xiàn)
創(chuàng)建api/getData文件夾
項(xiàng)目創(chuàng)建完成后在 app?文件下新建api文件夾,在 api 文件夾下新建 getData 文件夾,在 getData 文件夾下新建 route.js,這里面用于存儲(chǔ)我們的接口信息,如下
注意:在 Nuxt.js中,app文件夾通常用于存放應(yīng)用程序的配置和組件,而?api
文件夾則用于存放API路由處理程序。
當(dāng)我們?cè)?api
文件夾中創(chuàng)建子文件夾時(shí),Nuxt.js 會(huì)將這些子文件夾視為 API 的路徑的一部分。我們就可以直接將子文件夾的名稱作為 API 的路徑的一部分。
拿我們上面創(chuàng)建的舉例,我們?cè)陧?yè)面中請(qǐng)求的路徑就為:api/getData
route.js中寫接口信息
import { NextResponse } from 'next/server'
const mysql = require('mysql2/promise')
// 創(chuàng)建全局的 MySQL 連接池
const pool = mysql.createPool({
connectionLimit: 10,
host: '127.0.0.1', // 服務(wù)器地址
user: 'root',
password: '123456', // 密碼
database: 'jackson_blog_dev',
})
export async function GET(request) {
try {
// 從連接池中獲取連接
const connection = await pool.getConnection()
// 執(zhí)行 MySQL 查詢
const [rows, fields] = await connection.query('SELECT * FROM jacksonblogbacked')
// 釋放連接回連接池
connection.release()
return NextResponse.json({ data: rows }, { status: 200 })
} catch (error) {
console.error('Error:', error)
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
}
安裝 mysql2
安裝 mysql2 用于連接本地?cái)?shù)據(jù)庫(kù)
npm install mysql2
創(chuàng)建 mysql 連接,并把相應(yīng)信息填寫上
(這一步大家要按照自己的數(shù)據(jù)庫(kù)信息)
// 創(chuàng)建全局的 MySQL 連接池
const pool = mysql.createPool({
connectionLimit: 10,
host: '127.0.0.1', // 服務(wù)器地址
user: 'root',
password: '123456', // 密碼
database: 'jackson_blog_dev',
})
接下來(lái)就是從表中查詢數(shù)據(jù),我們使用 'next/server' 提供的 NextResponse 把數(shù)據(jù)以 json 對(duì)象的形式返回出去即可。
export async function GET(request) {
try {
// 從連接池中獲取連接
const connection = await pool.getConnection()
// 執(zhí)行 MySQL 查詢
const [rows, fields] = await connection.query('SELECT * FROM jacksonblogbacked')
// 釋放連接回連接池
connection.release()
return NextResponse.json({ data: rows }, { status: 200 })
} catch (error) {
console.error('Error:', error)
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
}
使用接口
現(xiàn)在我們已經(jīng)在把接口信息寫好了,如何在頁(yè)面中使用呢?
頁(yè)面中使用
接口已經(jīng)初始化好了,接下來(lái)就是在頁(yè)面中使用接口
在 app/page.tsx 中
'use client' //客戶端渲染時(shí)
import React, { useState, useEffect } from 'react'
const Home = () => {
const [data, setData] = useState([])
useEffect(() => {
fetchData()
}, [])
const fetchData = async () => {
try {
const response = await fetch('/api/getData')
const res = await response.json()
const data = res.data[0]
setData(data.title)
console.log('data: ', data)
} catch (error) {
console.error('Error fetching data:', error)
}
}
return (
<div>
<h1>測(cè)試mysql連接:{data}</h1>
</div>
)
}
export default Home
這里為了測(cè)試數(shù)據(jù)響應(yīng)渲染到頁(yè)面中,我們使用了useState鉤子函數(shù),需要在頂部加上 'use client' 表示在客戶端渲染即可。
我們直接使用fetch請(qǐng)求我們的接口,正如我上面所說(shuō)的,直接請(qǐng)求 /api/getData 這個(gè)接口地址即可,無(wú)需再進(jìn)行其他接口配置。
const fetchData = async () => {
try {
const response = await fetch('/api/getData')
const res = await response.json()
const data = res.data[0]
setData(data.title)
console.log('data: ', data)
} catch (error) {
console.error('Error fetching data:', error)
}
}
最后將得到的數(shù)據(jù)渲染到頁(yè)面中即可
const data = res.data[0]
setData(data.title)
效果如下:
總結(jié)
首先在 Next 中創(chuàng)建好接口文件,接口文件的模式按照 Next 所提供的接口格式進(jìn)行接口配置,最后在頁(yè)面中直接使用接口路徑使用即可。
以上就是如何使用 Next 框架實(shí)現(xiàn)一個(gè)簡(jiǎn)單的后端接口所有內(nèi)容,如果你感覺寫的還不錯(cuò)對(duì)你有幫助的話,可以點(diǎn)個(gè)贊支持一下,你的支持就是作者最大的動(dòng)力?!
源碼
所有代碼都已經(jīng)提交到 GitHub文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-835149.html
GitHub:chenyajun-create/next-mysql (github.com)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-835149.html
到了這里,關(guān)于使用 Next.js 連接 mysql 數(shù)據(jù)庫(kù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!