reactjs - Web config for Node js + react build for IIS Server - Stack Overflow

I am trying to deploy my node application on IIS server which is serving react build from publicmy-app

I am trying to deploy my node application on IIS server which is serving react build from public/my-app folder.

Below is my 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:
     .config
-->

<configuration>
  <system.webServer>
    <!-- WebSocket support configuration -->
    <webSocket enabled="false" />
    <iisnode nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />

    <!-- Handler configuration to use iisnode for Node.js applications -->
    <handlers>
      <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
    </handlers>

    <!-- URL Rewrite rules -->
    <rewrite>
      <rules>
        <!-- Rule to serve static content from the /public folder -->
        <rule name="StaticContent" stopProcessing="true">
          <match url="^(.*\.(js|css|png|jpg|gif|ico|html|json))$" />
          <action type="Rewrite" url="public/my-app/{R:0}" />
        </rule>

        <!-- Rule to serve index.html for directory requests -->
        <rule name="ServeIndexHtml" stopProcessing="true">
          <match url="(.*)/?$" />
          <conditions>
            <!-- Check if the request is for a directory -->
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="false" />
          </conditions>
          <action type="Rewrite" url="public/my-app/index.html" />
        </rule>

        <!-- Rule to route all other requests to the Node.js application -->
        <rule name="DynamicContent">
          <conditions>
            <!-- Ensure this rule only applies if the requested URL does not match a file -->
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <!-- Ensure this rule only applies if the requested URL does not match a directory -->
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>

    <!-- Request Filtering -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin" />
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Pass-through for error responses -->
    <httpErrors existingResponse="PassThrough" />

    <!-- iisnode configuration (optional) -->
    <!--<iisnode watchedFiles="web.config;*.js" node_env="production" debuggingEnabled="false" />-->
  </system.webServer>
</configuration>

This serves the index.html but my APIs are not working.

Here is my index.js code

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const app_1 = __importDefault(require("./app"));
const dotenv_1 = __importDefault(require("dotenv"));
const configure_log_1 = require("./utils/configure-log");
dotenv_1.default.config();
const PORT = process.env.PORT || 8080;
app_1.default.listen(PORT, () => __awaiter(void 0, void 0, void 0, function* () {
    configure_log_1.appLogger.info(`Server is running on port ${PORT}`);
}));

and below is my app.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const index_1 = __importDefault(require("./routes/index"));
const dotenv_1 = __importDefault(require("dotenv"));
const body_parser_1 = __importDefault(require("body-parser"));
const cors_1 = __importDefault(require("cors"));
const path_1 = __importDefault(require("path"));
const cookie_parser_1 = __importDefault(require("cookie-parser"));
dotenv_1.default.config();
const app = (0, express_1.default)();
app.use((0, cors_1.default)({
    // Adjust to the frontend URL
    origin: 'http://localhost:3000',
    // Allow sending cookies
    credentials: true,
}));
app.use(body_parser_1.default.json());
app.use((0, cookie_parser_1.default)());
// Increase request size limit and handle form data parsing
app.use(express_1.default.json({ limit: '500mb' }));
app.use(express_1.default.urlencoded({ extended: false }));
// Serve static files from the 'public' directory (for uploaded files, etc.)
app.use('/public', express_1.default.static(path_1.default.join(__dirname, 'public')));
// Serve your Angular/React app from 'my-app' (in the public folder)
app.use(express_1.default.static(path_1.default.join(__dirname, 'public', 'my-app')));
// Route for API requests
app.use('/api', index_1.default);
app.set('view engine', 'ejs');
// Serve the Angular/React app for the root and all other undefined routes (for SPA routing)
app.get('/test', (req, res) => {
    res.send('API is working!');
});
app.get('/', (req, res) => {
    res.sendFile(path_1.default.join(__dirname, 'public', 'my-app', 'index.html'));
});
app.get('*', (req, res) => {
    res.sendFile(path_1.default.join(__dirname, 'public', 'my-app', 'index.html'));
});
// Error handler for 404 - route not found
app.use((req, res) => {
    res.status(404).json({ message: 'Route not found' });
});
exports.default = app;

Above code is a build of typescript code. Please let me know what am I doing wrong.

I tried multiple web.configs but nothing worked, I even tried below web.config given by chatGPT, but that doesnt even serves index.html and gives 403 error

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <!-- Handler configuration to use iisnode for Node.js applications -->
    <handlers>
      <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
    </handlers>

    <!-- URL Rewrite rules -->
    <rewrite>
      <rules>
        <!-- Rule to serve static content from the 'public' directory -->
        <rule name="StaticContent" stopProcessing="true">
          <match url="^public/(.*)$" />
          <action type="Rewrite" url="public/{R:1}" />
        </rule>

        <!-- Rule to route API requests to Node.js application -->
        <rule name="APIContent" stopProcessing="true">
          <match url="^api/.*" />
          <action type="Rewrite" url="index.js" />
        </rule>

        <!-- Rule to route all other requests to the Node.js application -->
        <rule name="DynamicContent" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>

    <!-- Pass-through for error responses -->
    <httpErrors existingResponse="PassThrough" />

    <!-- iisnode configuration -->
    <iisnode loggingEnabled="true" devErrorsEnabled="true" />
  </system.webServer>
</configuration>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742305256a4418809.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信