关于使用Next遇到的一些新特性
用next之后发现,这是作为全栈比较好用的框架
API
1、app Router
这是目前next官方以及未来推荐的新技术方向
若使用api路由用来管理后端api接口
(1)此时在app文件夹下创建 api名称目录(如 getApiKey)
(2)文件夹名称为API名称
(2)其文件,根据约定每个api文件夹下的文件使用route.xxx 作为api文件,这就像页面路由或组件中,创建的是page.xxx(传统意义的index.xx)作为默认首页文件
注意: 在 Next.js 13 和 14 中,引入了新的 app 目录和 Route Handlers,这些新特性改变了处理 API 请求的方式。使用 app 目录中的 API 路由时,建议使用 NextResponse 来处理响应,而不是传统的 res.json() 方法。
如:
// app/getApiKey/route.ts// 获取apiKey API
// 请求方式:GET
// 请求地址:/getApiKey
// 请求参数: all or name
// 返回数据:[{ name: 'ChatGpt', value: 'sk-xxxxxx' }]import { NextResponse } from 'next/server';export async function GET(req, res) {const { searchParams } = new URL(req.url);const name = searchParams.get('name');// 返回数据 使用 mogonDB 数据库if (name) {// 获取指定apiKey}else {const data = [{name: 'ChatGpt',value: 'sk-xxxxxx'},{name: 'QianWen',value: 'sk-xxxxxx'}]// 获得所有apiKey return NextResponse.json(res, { status: 200 })}
}
2、pages 传统路由
这种常用传统方式
(1)依然在pages目录创建api文件
(2)但采用的文件名为API访问名称
(3)其中需要手动拿req来分辩get或其它method
(4)只需要导出接口函数,名称可随意命名
注意:包含 res传统返回
// pages/api/getApiKey.js
import { MongoClient } from 'mongodb';const uri = process.env.MONGODB_URI;async function getApiKey(req, res) {if (req.method !== 'GET') {return res.status(405).json({ message: 'Method Not Allowed' });}const { name } = req.query;try {const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });await client.connect();const db = client.db('your-database-name');const collection = db.collection('apikeys');if (name) {// 获取指定的 API Keyconst apiKey = await collection.findOne({ name: name });if (!apiKey) {return res.status(404).json({ message: 'API Key not found' });}return res.status(200).json(apiKey);} else {// 获取所有 API Keysconst apiKeys = await collection.find({}).toArray();return res.status(200).json(apiKeys);}} catch (error) {console.error('Error fetching API keys:', error);return res.status(500).json({ message: 'Internal Server Error' });}
}export default getApiKey;