Nextjs: https://nextjs.org/ (opens in a new tab) GitHub starslast commit

类库

  1. next-connect (opens in a new tab): 灵活中间件和路由处理程序库。GitHub starslast commitnpm downloads

Real World

App Router

  1. ChatGPT-Next-Web (opens in a new tab): 一键拥有你自己的跨平台 ChatGPT 应用。GitHub starslast commit

技巧

路由跳转

"use client";
import { useRouter } from "next/navigation";
const router = useRouter();
router.push("/dashboard");

代理请求

所有需要代理的请求都通过/proxy/[...slug]路由转发到[...slug]

// proxy/[...slug]/route.ts
 
import { NextRequest, NextResponse } from "next/server";
import got, { Method } from "got";
 
const defaultEndpoint = "http://xx.xx.xx.x:2000";
 
async function proxy(
  request: NextRequest,
  { params }: { params: { slug: string[] } }
) {
  const slug = params.slug;
  const method = request.method.toLowerCase() as Method;
  const searchParams = request.nextUrl.searchParams;
  let json;
  try {
    json = await request.json();
  } catch (e) {}
  const endpoint = searchParams.get("endpoint") || defaultEndpoint;
 
  const path = slug.join("/");
  const url = `${endpoint}/${path}`;
  console.log(method, url);
  const res = await got(url, {
    method: method,
    json: json,
  }).json();
  return NextResponse.json(res);
}
 
export const GET = proxy;
export const POST = proxy;
export const DELETE = proxy;

文件上传

import { NextResponse } from "next/server";
import { v4 as uuid } from "uuid";
import path from "path";
import fs from "fs-extra";
 
export const POST = async (req: Request) => {
  const form = await req.formData();
  const file = form.get("file") as File;
  const arrayBuffer = await file.arrayBuffer();
  const bufer = Buffer.from(arrayBuffer);
  const dataDir = path.resolve(process.cwd(), ".data/data-handle-files");
  await fs.ensureDir(dataDir);
  const filename = `${uuid()}.zip`;
  const filepath = path.join(dataDir, filename);
  fs.writeFileSync(filepath, bufer);
 
  return NextResponse.json({ success: true, filename });
};