一、安裝全局依賴
npm i -g create-next-app
二、創(chuàng)建next項目
create-next-app react-next-demo
//或
create-next-app react-next-demo --typescript
三、加載mysql依賴
npm i -S mysql2
四、運行項目
npm run dev
五、創(chuàng)建db文件目錄,目錄下創(chuàng)建index.ts
import { createConnection } from "mysql2";
// 創(chuàng)建數(shù)據(jù)庫連接
const db = createConnection({
host: 'localhost', // 數(shù)據(jù)庫主機名
user: 'root', // 數(shù)據(jù)庫用戶名
password: 'password', // 數(shù)據(jù)庫密碼
database: 'mydb' // 數(shù)據(jù)庫名稱
});
// 連接到數(shù)據(jù)庫
db.connect((err) => {
if (err) {
console.error('無法連接到數(shù)據(jù)庫:', err);
return;
}
console.log('已成功連接到數(shù)據(jù)庫');
});
module.exports = db;
六、創(chuàng)建pages文件目錄,目錄下創(chuàng)建api文件目錄,api目錄下創(chuàng)建user.ts
請求地址 http://localhost:3000/api/user
import db from "@/db";
import { NextApiRequest, NextApiResponse } from "next";
export default (req: NextApiRequest, res: NextApiResponse) => {
db.query(`SELECT * FROM ....`, (err, result) => {
res.status(200).json(result)
})
};
七、在pages目錄下創(chuàng)建user.tsx
頁面訪問地址 http://localhost:3000/user文章來源:http://www.zghlxwxcb.cn/news/detail-731060.html
import { useEffect } from "react"
export default () => {
useEffect(() => {
fetch(`api/user`).then(res => {
console.log(res) //接口數(shù)據(jù)
})
}, [])
return <div>Hello Next.js</div>
}
Tip 目錄結(jié)構(gòu)
文章來源地址http://www.zghlxwxcb.cn/news/detail-731060.html
到了這里,關(guān)于React+Node——next.js 構(gòu)建前后端項目的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!