Next.js生产环境部分API失效,部署后博客页面无法正常渲染求助
Next.js生产环境API请求失败(开发环境正常)
问题背景
开发环境下博客详情页渲染正常,但部署到生产环境后,页面无法获取后端API数据,导致无法正常显示内容。
相关信息:
- 后端API地址:
https://mutfakci.westhospital.az/api/blog - 前端博客详情页地址:
https://front.westhospital.az/blog/1
相关代码
博客页面代码
const Detail = ({ article }) => { console.log(article); return ( <section id="blog_detail"> <div className="container-fluid"> <div className="row"> <div className="col-lg-12 p-0"> <div className="dtail_img"> <img src="/FORWEB01 1 (1).png" alt="" /> </div> </div> </div> </div> <BlogDetailMain article={article} /> {/* <LatesBlog/> */} <Coporation /> </section> ); }; export default Detail; export const getStaticProps = async (context) => { const res = await fetch(`${server}/api/blog/${context.params.id}`); const responseData = await res.json(); const article = responseData.data; return { props: { article, }, }; }; export const getStaticPaths = async () => { const res = await fetch(`${server}/api/blog`); const articlesResponse = await res.json(); const articles = articlesResponse.data; const ids = articles.map((article) => article.id); const paths = ids.map((id) => ({ params: { id: id.toString() } })); return { paths, fallback: false, }; };
部署文件dep.js
const { createServer } = require('http') const { parse } = require('url') const next = require('next') const dev = process.env.NODE_ENV !== 'production' const hostname = process.env.NODE_ENV !== "production" ? 'localhost' : 'front.westhospital.az' const port = process.env.NODE_ENV || 5522 // when using middleware `hostname` and `port` must be provided below const app = next({ dev, hostname, port }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer(async (req, res) => { try { // Be sure to pass `true` as the second argument to `url.parse`. // This tells it to parse the query portion of the URL. const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl if (pathname === '/a') { await app.render(req, res, '/a', query) } else if (pathname === '/b') { await app.render(req, res, '/b', query) } else { await handle(req, res, parsedUrl) } } catch (err) { console.error('Error occurred handling', req.url, err) res.statusCode = 500 res.end('internal server error') } }).listen(port, (err) => { if (err) throw err console.log(`> Ready on http://${hostname}:${port}`) }) })
Next.js配置文件
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, } module.exports = nextConfig
package.json脚本部分
"scripts": { "dev": "node dep.js", "build": "next build", "start": "NODE_ENV=production node dep.js" },
问题分析
- 未定义的
server变量:页面代码中getStaticProps和getStaticPaths使用了${server}拼接API地址,但未定义该变量。开发环境可能通过全局变量或其他方式注入了值,但生产环境未配置,导致请求地址无效。 - 部署文件端口配置错误:
dep.js中port = process.env.NODE_ENV || 5522,生产环境下process.env.NODE_ENV为production,会将端口设为字符串production,导致服务器无法正常启动。 - 构建时API可达性:
getStaticProps和getStaticPaths在next build阶段执行,若构建环境无法访问后端API,会导致静态页面生成失败。
解决方案
1. 配置API环境变量
在项目根目录创建.env.production文件,定义后端API基础地址:
NEXT_PUBLIC_API_BASE_URL=https://mutfakci.westhospital.az
修改博客页面代码中的请求地址,使用环境变量替代server:
export const getStaticProps = async (context) => { const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/blog/${context.params.id}`); // 其余代码不变 }; export const getStaticPaths = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/blog`); // 其余代码不变 };
2. 修复部署文件端口配置
修改dep.js中的端口赋值逻辑,确保生产环境使用正确端口:
const port = parseInt(process.env.PORT, 10) || 5522
3. 确保构建环境可访问后端API
确认执行next build的服务器能够访问https://mutfakci.westhospital.az/api/blog,若存在网络限制,需开放对应权限。
4. 检查后端CORS配置(若有客户端请求)
如果页面后续存在客户端侧API请求,需确保后端配置了CORS规则,允许front.westhospital.az域名访问。
内容的提问来源于stack exchange,提问作者Feremez Bagırov
相关产品推荐
相关产品推荐

