nextjs

264 阅读2分钟

next经常被用作是ssr或者是服务端应用,这个就很值得一说了。现在很多人原因用他做全栈,但是网上的教程就很扯淡,都是只注重于ssr,和使用文件读取的一面,其他服务端的,接口都很少涉及,找都难找,中文文档还很过时。 那么现在,nextjs14出现了,被人群嘲,但是我觉得还是有省级的。

初始化

开始做吧,首先,简单一个cli,

 npx create-next-app@latest
What is your project named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias (@/*)? No / Yes
What import alias would you like configured? @/*

一般使用默认的就行了,而14强调app route,那我们也就用它

页面

注意点,app route下自动创建的app文件夹下,用page来识别组件 image.png 约定式路由再更改,app下,文件夹命名代表路由,往下走也就是page.js,类似于以前的index.js image.png

引入ant5.0

这个就比较魔幻了,官网是有支持使用next的,但是对next14的approuter还没有更细的支持文档。 layout.tsx

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { AntdRegistry } from "@ant-design/nextjs-registry";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "build nn app",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="cn">
      <body className={inter.className}>
        <AntdRegistry>{children}</AntdRegistry>
      </body>
    </html>
  );
}

注意了,上面都还是用官网写法正常,如果你有主题,前缀,更改,那就比较麻烦了。一定不能在layout.tsx中使ConfigProvider,否则会报错,要去二级的,比如page等。

服务api

image.png

这就是最奇怪的点了,其他的文档里几乎不写这个,api的服务是,定义和使用方法是,使用route.ts,这样你就能在page代码中直接去fetch调用了,当然,如果你使用14推荐的server action,那这里就忽略

fetch("/kkk/getList", { method: "post" }).then(async (res) => {
  console.log("结果", await res.json());
});

/kkk/getList/route.ts

'use server';

import { NextRequest, NextResponse } from "next/server";
import fs from "node:fs";
import path from 'node:path';

async function service(){
  console.log('first,', path.join(process.cwd(), '../'))
  const t = fs.readdirSync(path.join(process.cwd(), '../'));
  return NextResponse.json({data: t}, {status: 200})
};

export async function GET(request:NextRequest){
  console.log('get请求')
  return await service()
}
export async function POST(){
  console.log('post请求')
  return await service()
}

注意,这里不能使用

export default async function(){}

这样的会报 Detected default export in '/Users/xxxx/app/kkk/getList/route.ts'. Export a named export for each HTTP method instead. ​