Приложение NextJs не загружает изображение в общедоступную папку nextjs при развертывании в веб-приложении Azure

Изображения, такие как png, успешно отображаются в приложении при локальном запуске next build + next start но после его развертывания в веб-приложении Azure через server.js и web.config изображения больше не загружаются.

У меня есть мое изображение под public/imgs/logo.png и я ссылаюсь на это так: <Image src={'/imgs/logo.png'} height={'20px'} width={'180px'} />

Я даже пробовал запустить server.js напрямую( node server.js) после того, как все будет построено, а изображение все еще загружается. Но как только я загружаю файлы сборки (папку .next), web.config и server.js в свое веб-приложение Azure, изображение больше не загружается.

Пожалуйста помоги. Ниже приведены некоторые файлы, которые я использовал для этого.

server.js

      const { createServer } = require("http");
// const express = require('express') (Only if you app uses express)
const next = require("next");

const port = process.env.PORT || 8888;
const isDev = process.env.ENV !== "production";
const app = next({ isDev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    handle(req, res);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`Ready on http://localhost:${port}`);
  });
});

web.config

      <?xml version="1.0" encoding="utf-8"?>
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config>
-->

<configuration>
  <system.webServer>
    <!-- Visit <http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx> for more information on WebSocket support -->
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\\/debug[\\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config> for a full list of options
    -->
    <iisnode watchedFiles="web.config;*.js"/>
  </system.webServer>
</configuration>

next.config.js

      const path = require("path");
require("dotenv").config();
const withImages = require("next-images");

module.exports = withImages({
  reactStrictMode: true,
  eslint: {
    dirs: ["apiclients", "common", "components", "config", "pages", "stores"],
  },
  sassOptions: {
    includePaths: [
      path.join(__dirname, "styles"),
      path.join(__dirname, "components"),
    ],
    prependData: `@import "styles/_variables";`, // prepend _css variables in all css documents
  },
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.plugins.push(new webpack.EnvironmentPlugin(process.env));
    return config;
  },
  experiments: {
    asset: true,
  },
});

1 ответ

Компонент (next/image) зависит от работающего Next Server. Если вы экспортируете его в любой статической конфигурации, размещенной другой службой, он терпит неудачу (если вы не выполните какое-либо специальное кодирование для обработки изображений). Я создал программу php, которая перенаправляет изображения из папки /_next/assets/ в моих обстоятельствах, но вы также должны проверить, замените один из тегов <Image тегом <img и посмотрите, правильно ли отображается это изображение. Если да, то это ваша проблема. Затем вы можете заменить все свои теги, но вы потеряете некоторые преимущества, такие как отложенная загрузка и т. Д.

Другие вопросы по тегам