我在 next JS 中(在 pages/api
文件夹中)创建了一个 API,并在 pages
文件夹中的页面上使用了它。
当我在localhost(开发阶段)上运行时,可以正确调用API。但是当我部署到 Vercel 时,构建过程中出现错误。
这是我调用位于 pages/api
文件夹中的 API 时的代码
export const getStaticProps = async () => {
const baseUrlDribble = 'https://api.dribbble.com/v2';
const baseUrl = process.env.NODE_ENV === 'production' ?
'https://jovanka-samudra.vercel.app/api' : 'http://localhost:3000/api';
const resShots = await fetch(`${baseUrlDribble}/user/shots?access_token=${process.env.TOKEN_DRIBBLE}&page=1&per_page=9`);
const shots = await resShots.json();
const resResult = await fetch(`${baseUrl}/projects`);
const result = await resResult.json();
const projects = result.data.projects;
return {
props: {
shots,
projects,
},
revalidate: 1,
}
}
这是从数据库(pages/api/projects
文件夹)检索数据的 API 代码
import ProjectService from "@services/ProjectService";
import connectDB from "@utils/connectDB";
import projectValidator from "@validators/project";
import ClientError from '@exceptions/ClientError';
const handler = async (req, res) => {
const projectService = new ProjectService();
if (req.method === 'GET') {
try {
const projects = await projectService.getProjects();
return res.status(200).json({
success: true,
length: projects.length,
data: {
projects
}
});
} catch (error) {
return res.status(500).json({
success: false,
message: error.message,
});
}
} else if (req.method === 'POST') {
...
}
return res.status(404).json({
success: false,
message: 'Method not alowed'
});
}
export default connectDB(handler);
services/ProjectService 文件夹
import InvariantError from '@exceptions/InvariantError';
import NotFoundError from '@exceptions/NotFoundError';
import Project from '@models/Project';
class ProjectService {
async getProjects() {
const projects = await Project.find().sort({ 'createdAt': -1 });
return projects;
}
...
}
export default ProjectService;
答案 0 :(得分:1)
您不应从 getStaticProps 获取内部 API 路由 - 相反,您可以直接在 getStaticProps 中编写 API 路由中的获取代码。
https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly