Gun*_*niX 0 error-handling public nextjs-image next.js13
一切都很好,翻译了 nextjs13.4、tailwindcss 和 i18n 中的所有内容,我没有使用打字稿,但我的图像尽管位于公共文件夹中,却无法加载到任何地方。
我在控制台中收到错误: GET http://localhost:3000/_next/image?url=%2Fimagentest.jpg&w=128&q=75 400 (错误请求)
指南:https://locize.com/blog/next-13-app-dir-i18n/
我希望你能帮助我如何修复此代码错误
小智 7
这对我有用:
添加 const PUBLIC_FILE 并添加一个“if”:
import { NextResponse } from 'next/server'
import acceptLanguage from 'accept-language'
import { fallbackLng, languages } from './app/i18n/settings'
acceptLanguage.languages(languages)
const PUBLIC_FILE = /\.(.*)$/
export const config = {
matcher: ['/((?!api|_next/static|_next/public|_next/image|assets|favicon.ico|sw.js).*)']
}
const cookieName = 'i18next'
export function middleware(req) {
let lng
if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName).value)
if (!lng) lng = acceptLanguage.get(req.headers.get('Accept-Language'))
if (!lng) lng = fallbackLng
//to take the files from the publisc folder
if (
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return
}
// Redirect if lng in path is not supported
if (
!languages.some(loc => req.nextUrl.pathname.startsWith(`/${loc}`)) &&
!req.nextUrl.pathname.startsWith('/_next')
) {
return NextResponse.redirect(new URL(`/${lng}${req.nextUrl.pathname}`, req.url))
}
if (req.headers.has('referer')) {
const refererUrl = new URL(req.headers.get('referer'))
const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`))
const response = NextResponse.next()
if (lngInReferer) response.cookies.set(cookieName, lngInReferer)
return response
}
return NextResponse.next()
}Run Code Online (Sandbox Code Playgroud)