来自下一个/图像的 400 错误请求

emm*_*mma 20 image reactjs next.js nextjs-image

所以我试图用 next/image 的组件显示图像。但是,图像并未显示。我相信这是因为 next/image 给了我一个 400 bad request 错误。

在此输入图像描述

当我单击该 URL 时,它显示“请求的资源不是有效图像”,这很奇怪,因为从后端检索图像 url 后,我能够下载图像以查看它是有效图像,所以此错误是在将图像链接传递到组件的 props 中之后发生的。基本上,我的请求是正确的,但是 next/image 与图像 url 的交互被搞乱了。奇怪的是,几天前我也没有出现此错误,在没有更改任何内容后,我看到了此错误。

我已经像这样配置了 next.js 配置文件,并且对后端的请求确实检索了可下载的图像(next/image 只是没有正确显示)。

这是我的 next.js 配置文件:

const withPlugins = require('next-compose-plugins');
const withImages = require('next-images');

const nextConfig = {
  images: {
    domains: [
      'url.s3.amazonaws.com',
      'url.s3.amazonaws.com',
      'url.s3.amazonaws.com',
    ],
  },
  
};


module.exports = withPlugins([[withImages]], nextConfig);
Run Code Online (Sandbox Code Playgroud)

doa*_*nnx 6

我迟到了,但希望我的回答对其他人有帮助。

将域的配置添加到 next.config.js 中是不够的(仅适用于本地):

module.exports = {
  ...
  images: {
    domains: ['firebasestorage.googleapis.com'],
  }
}
Run Code Online (Sandbox Code Playgroud)

对于生产,您需要确保您的“下一个”实例获取该配置。

因此,就我而言,我为使其发挥作用所做的事情是:

const nextjsDistDir = join("src", require("./src/next.config.js").distDir);
const nextjsServer = next({
  dev: isDev,
  conf: {
    distDir: nextjsDistDir
  }
});
Run Code Online (Sandbox Code Playgroud)

const nextjsDistDir = join("src", require("./src/next.config.js").distDir);
const nextjsServer = next({
  dev: isDev,
  conf: {
    distDir: nextjsDistDir,
    images: {
      domains: ['firebasestorage.googleapis.com'],
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 这些更改位于哪个文件中? (11认同)

AiU*_*AiU 5

就我而言,此问题仅发生在 docker 容器中。\n事实证明,问题是Dockerfile没有复制next.config.js我配置图像优化的 \xc2\xa0 文件。

\n

基本上,它缺少这一行:

\n
COPY --from=builder /app/next.config.js ./\n
Run Code Online (Sandbox Code Playgroud)\n

这是Dockerfile我使用的:

\n
FROM node:18-alpine AS deps\nRUN apk add --no-cache libc6-compat\nWORKDIR /app\n\nCOPY package.json package-lock.json ./\nCOPY public ./public\nRUN  npm install --production\n\nFROM node:18-alpine AS builder\nWORKDIR /app\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY . .\n\nENV NEXT_TELEMETRY_DISABLED 1\n\nRUN npm run build\n\nFROM node:18-alpine AS runner\nWORKDIR /app\n\nENV NODE_ENV production\nENV NEXT_TELEMETRY_DISABLED 1\n\nRUN addgroup --system --gid 1001 nodejs\nRUN adduser --system --uid 1001 nextjs\n\nCOPY --from=builder --chown=nextjs:nodejs /app/.next ./.next\nCOPY --from=builder /app/next.config.js ./\nCOPY --from=builder /app/node_modules ./node_modules\nCOPY --from=builder /app/public ./public\nCOPY --from=builder /app/package.json ./package.json\n\nUSER nextjs\n\nEXPOSE 3000\n\nENV PORT 3000\nENV NODE_ENV production\n\nCMD ["npm", "start"]\n\n
Run Code Online (Sandbox Code Playgroud)\n

如果这对您有帮助,请记得投票并选择正确答案

\n


小智 0

你更新了nextjs版本了吗?似乎 10.1.X 和更新版本有一些问题... https://github.com/vercel/next.js/issues/23523