为静态网站构建生产时出现nextjs错误 [英] nextjs error when build production for static website
问题描述
当我导出为生产 npm run build
时,我不明白这些错误,但是当我测试 npm run dev
时,它工作得很好.我使用 getStaticProps
和 getStaticPath
从 api
首先当我npm run build
FetchError:https://main-website-next.vercel.app/api/products 处的 json 响应正文无效原因:JSON 中的意外标记 T 位于位置0在 D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:272:32在 processTicksAndRejections (internal/process/task_queues.js:97:5)在 async getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\product\[slug].js:1324:18)在 async buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:80)在异步 D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:612在异步 D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {类型:'无效-json'}
\pages\product[slug]
import { assetPrefix } from '../../next.config'导出默认函数 Page(){...}export const getStaticProps = async ({ params: { slug }, locale }) =>{const res = await fetch(`${assetPrefix}/api/products/${slug}`)const 结果 = 等待 res.json()const data = result.filter(item => item.locale === locale)[0]const { 标题、关键字、描述 } = 数据返回 {道具: {数据,描述,关键字,标题}}}export const getStaticPaths = async() =>{const res = await fetch(`${assetPrefix}/api/products`)const 结果 = 等待 res.json()const 路径 = result.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))返回 {后备:真的,路径,}}
next.config.js
const isProd = process.env.NODE_ENV === '生产'模块.出口 = {资产前缀: isProd ?'https://main-website-next.vercel.app' : 'http://localhost:3000',国际化:{区域检测:假,语言环境:['en', 'th'],defaultLocale: 'en',}}
<块引用>
添加更多信息
//pages/api/products/index.js从../../../data/products"导入数据导出默认值 (req, res) =>{res.status(200).json(数据)}//pages/api/products/[slug].js从../../../data/products"导入数据库导出默认值({查询:{slug}},res)=>{const data = db.filter(item => item.slug === slug)如果(数据长度> 0){res.status(200).json(数据)} 别的 {res.status(404).json({ message: `${slug} not found` })}}//../../../data/products(数据源)模块.exports = [{ locale: "en", slug: "google-sheets-combine-your-cashflow",标题:结合你的现金流",关键字:[Google 表格"、会计"]、描述:……",},...]
第二次当我删除生产域时,我 npm run build
但仍然得到像
TypeError: 仅支持绝对 URL在 getNodeRequestOptions (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1305:9)在 D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1410:19在新承诺(<匿名>)在 fetch (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1407:9)在 getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\[slug].js:938:21)在 buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:86)在 D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:618在 processTicksAndRejections (internal/process/task_queues.js:97:5)在异步 D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {类型:'类型错误'}
删除后我的next.config.js
const isProd = process.env.NODE_ENV === '生产'module.exports = {//移除资产前缀: isProd ?'' : 'http://localhost:3000',国际化:{区域检测:假,语言环境:['en', 'th'],defaultLocale: 'en',}}
我的 package.json
当我 npm run build
脚本
<代码>{名称":主网站-下一个",版本":0.1.0",私人":真的,脚本":{开发":下一个开发",构建":下一个构建&&"下一个出口",开始":下次开始"},依赖关系":{下一个":10.0.6",反应":17.0.1",react-dom":17.0.1";}}
正如评论中提到的,你应该直接在 getStaticProps
/getStaticPaths
中使用你的 API 逻辑,因为这些也发生在服务器端.
///pages/product/[slug]从../../../data/products"导入数据库//剩余代码..export const getStaticProps = async ({ params: { slug }, locale }) =>{const 结果 = db.filter(item => item.slug === slug)const data = result.filter(item => item.locale === locale)[0]const { 标题、关键字、描述 } = 数据返回 {道具: {数据,描述,关键字,标题}}}export const getStaticPaths = async() =>{const 路径 = db.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))返回 {后备:真的,路径,}}
来自 Next.js 文档:
<块引用>您不应该使用 fetch() 在 getStaticProps 中调用 API 路由.相反,直接导入 API 路由中使用的逻辑.您可能需要为这种方法稍微重构您的代码.可以从外部 API 获取数据!
I don't understand these errors when I export as production npm run build
, but when I test npm run dev
it works just fine. I use getStaticProps
and getStaticPath
fetch from api
First when I npm run build
FetchError: invalid json response body at https://main-website-next.vercel.app/api/products reason: Unexpected token T in JSON at position
0
at D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:272:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\product\[slug].js:1324:18)
at async buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:80)
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:612
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {
type: 'invalid-json'
}
\pages\product[slug]
import { assetPrefix } from '../../next.config'
export default function Page(){...}
export const getStaticProps = async ({ params: { slug }, locale }) => {
const res = await fetch(`${assetPrefix}/api/products/${slug}`)
const result = await res.json()
const data = result.filter(item => item.locale === locale)[0]
const { title, keywords, description } = data
return {
props: {
data,
description,
keywords,
title
}
}
}
export const getStaticPaths = async () => {
const res = await fetch(`${assetPrefix}/api/products`)
const result = await res.json()
const paths = result.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))
return {
fallback: true,
paths,
}
}
next.config.js
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
assetPrefix: isProd ? 'https://main-website-next.vercel.app' : 'http://localhost:3000',
i18n: {
localeDetection: false,
locales: ['en', 'th'],
defaultLocale: 'en',
}
}
add more info
// pages/api/products/index.js
import data from '../../../data/products'
export default (req, res) => {
res.status(200).json(data)
}
// pages/api/products/[slug].js
import db from '../../../data/products'
export default ({ query: { slug } }, res) => {
const data = db.filter(item => item.slug === slug)
if (data.length > 0) {
res.status(200).json(data)
} else {
res.status(404).json({ message: `${slug} not found` })
}
}
// ../../../data/products (data source)
module.exports = [
{ locale: "en", slug: "google-sheets-combine-your-cashflow",
title: "Combine your cashflow",
keywords: ["Google Sheets","accounting"],
description: "...",
},
...
]
Second when I remove the production domain, I npm run build
but still get the error like
TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1305:9)
at D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1410:19
at new Promise (<anonymous>)
at fetch (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1407:9)
at getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\[slug].js:938:21)
at buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:86)
at D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:618
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {
type: 'TypeError'
}
my next.config.js
after remove
const isProd = process.env.NODE_ENV === 'production'
module.exports = { //remove
assetPrefix: isProd ? '' : 'http://localhost:3000',
i18n: {
localeDetection: false,
locales: ['en', 'th'],
defaultLocale: 'en',
}
}
my package.json
when I npm run build
script
{
"name": "main-website-next",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build && next export",
"start": "next start"
},
"dependencies": {
"next": "10.0.6",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
As mentioned in the comments, you should use your API logic directly in getStaticProps
/getStaticPaths
as these also happen server-side.
// /pages/product/[slug]
import db from '../../../data/products'
// Remaining code..
export const getStaticProps = async ({ params: { slug }, locale }) => {
const result = db.filter(item => item.slug === slug)
const data = result.filter(item => item.locale === locale)[0]
const { title, keywords, description } = data
return {
props: {
data,
description,
keywords,
title
}
}
}
export const getStaticPaths = async () => {
const paths = db.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))
return {
fallback: true,
paths,
}
}
From Next.js documentation:
You should not use fetch() to call an API route in getStaticProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!
这篇关于为静态网站构建生产时出现nextjs错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!