1:创建工程文件
npx create-next-app@latest
2:安装 axios
npm install axios
3:设置next.config配置文件
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
basePath: '/test',
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://domain.com/api/:path*',
basePath: false,// 这里的 example.com 是 API 的域名
},
];
},
};
export default nextConfig;
4:编写请求后台接口代码
'use client'
import exp from "constants";
import Image from "next/image";
import axios from 'axios';
export default function Home() {
const test = async()=>{
const {data} = await axios.post('/api/xxx', {
user:'2323243'
}, {
headers: {
'Content-Type': 'application/json'
}
})
console.log("Testing=========",data);
}
function handleClick() {
console.log("increment like count")
test();
}
return (
<main className="bg-white-100">
<div className="bg-red-800">
<button onClick={handleClick}>Like</button>
</div>
</main>
);
}
参考文档https://nextjs.org/docs/pages/api-reference/next-config-js/rewrites#rewrites-with-basepath-support