api router
基本使用
// /api/blog/[slug]/route.js
import { Post } from "@/lib/models";
import { connectToDb } from "@/lib/utils";
import { NextResponse } from "next/server";
// {params} 截获fetch路径中的参数
export const GET = async (request, { params }) => {
const { slug } = params;
try {
connectToDb();
const post = await Post.findOne({ slug });
return NextResponse.json(post);
} catch (err) {
console.log(err);
throw new Error("Failed to fetch post!");
}
};
export const DELETE = async (request, { params }) => {
const { slug } = params;
try {
connectToDb();
await Post.deleteOne({ slug });
return NextResponse.json("Post deleted");
} catch (err) {
console.log(err);
throw new Error("Failed to delete post!");
}
};
// page.jsx fetch api
import Image from "next/image";
import styles from "./singlePost.module.css";
import PostUser from "@/components/postUser/postUser";
import { Suspense } from "react";
import { getPost } from "@/lib/data";
// FETCH DATA WITH AN API
const getData = async (slug) => {
const res = await fetch(`http://localhost:3000/api/blog/${slug}`);
if (!res.ok) {
throw new Error("Something went wrong");
}
return res.json();
};
export const generateMetadata = async ({ params }) => {
const { slug } = params;
const post = await getPost(slug);
return {
title: post.title,
description: post.desc,
};
};
const SinglePostPage = async ({ params }) => {
const { slug } = params;
// FETCH DATA WITH AN API
const post = await getData(slug);
其中需要注意的是可以将api服务器地址设置为环境变量
使用server action还是api router
server action能完全替代fetch api吗?
api可以更好的实现多个平台共用后端服务的情况