可以为Net6+ t lauch spa代理React应用程序

发布于 2025-02-11 08:25:52 字数 6411 浏览 2 评论 0原文

我正在创建一个基于ASP.NET Core Web应用程序 + React模板的新项目。然后,我为我的需求配置客户端 - CRA的Innstead我使用我自己的webpack.config.js。 Frontend正常工作,当我使用npm start运行时,它会按预期启动。但是后端不会推出。问题来自水疗代理,该代理无法正常工作。当我启动应用程序时,我会收到以下消息:SPA代理还没有准备好。返回临时着陆页。同时,前端页面可以正确打开,但是没有代理服务器,该应用程序基本上无法运行。有什么想法我缺少什么?

{
  "name": "project1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open --mode development --hot",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.17.9",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-loader": "^8.2.4",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.6.0",
    "node-sass": "^7.0.1",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "sass": "^1.51.0",
    "sass-loader": "^12.6.0",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.2.8",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.8.1"
  },
  "dependencies": {
    "@fluentui/react": "^8.65.0",
    "@types/react": "^18.0.5",
    "@types/react-dom": "^18.0.0",
    "typescript": "^4.6.3"
  }
}

内容

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
    <SpaProxyServerUrl>http://localhost:5206</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="6.0.6" />
  </ItemGroup>

  <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)build\**" />
      <ResolvedFileToPubliFsh Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPubliFsh>
    </ItemGroup>
  </Target>
</Project>

我的

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackDevServerPort = 8083;
const proxyTarget = "http://localhost:5206";

module.exports = {
    mode: 'development',
    entry: './index.tsx',
    devtool: 'inline-source-map',
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
    },
    devtool: 'inline-source-map',
    devServer: {
        static: './dist',
        proxy: {
            '*': {
                target: proxyTarget
            }
        },
        port: webpackDevServerPort
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(s*)css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ]
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    plugins:[
        new HtmlWebpackPlugin({
        template: './index.html'
        })
    ]
}

软件包的

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:45536",
      "sslPort": 44368
    }
  },
  "profiles": {
    "Project1": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5206",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  }
}

I'm creating a new project based on ASP.NET CORE Web Application + React template. Then I configure ClientApp for my needs - innstead of CRA I use my own webpack.config.js. Frontend works fine, it launches as expected when I run it with npm start. But backend won't launch. The problem comes from SPA Proxy which is not working properly. When I start the app I get the following message: SPA proxy is not ready. Returning temporary landing page. Meanwhile the frontend page opens correctly, but without proxy server the app basically doesn't run. Any ideas what I am missing?

The content of my package.json file:

{
  "name": "project1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open --mode development --hot",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.17.9",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-loader": "^8.2.4",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.6.0",
    "node-sass": "^7.0.1",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "sass": "^1.51.0",
    "sass-loader": "^12.6.0",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.2.8",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.8.1"
  },
  "dependencies": {
    "@fluentui/react": "^8.65.0",
    "@types/react": "^18.0.5",
    "@types/react-dom": "^18.0.0",
    "typescript": "^4.6.3"
  }
}

The content of .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
    <SpaProxyServerUrl>http://localhost:5206</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="6.0.6" />
  </ItemGroup>

  <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)build\**" />
      <ResolvedFileToPubliFsh Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPubliFsh>
    </ItemGroup>
  </Target>
</Project>

webpack.config.js file:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackDevServerPort = 8083;
const proxyTarget = "http://localhost:5206";

module.exports = {
    mode: 'development',
    entry: './index.tsx',
    devtool: 'inline-source-map',
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
    },
    devtool: 'inline-source-map',
    devServer: {
        static: './dist',
        proxy: {
            '*': {
                target: proxyTarget
            }
        },
        port: webpackDevServerPort
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(s*)css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ]
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    plugins:[
        new HtmlWebpackPlugin({
        template: './index.html'
        })
    ]
}

launchsettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:45536",
      "sslPort": 44368
    }
  },
  "profiles": {
    "Project1": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5206",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

音盲 2025-02-18 08:25:52
  1. 打开您的clientapp目录。

  2. 在终端中运行以下命令:

npm i spa-proxy


如果以上解决方案失败,请尝试以下操作:

  1. 打开client appapp目录。

  2. 在终端中运行以下命令:

NPM Update

  1. Open your ClientApp directory.

  2. Run the following command in terminal:

npm i spa-proxy


If the solution above fails, try this:

  1. Open your ClientApp directory.

  2. Run the following command in terminal:

npm update

淡淡的优雅 2025-02-18 08:25:52

有时候,当我们从另一个人那里获取项目或从互联网下载项目并尝试运行我们的项目时,就会出现这个问题。
您可以通过打开.env.development.Local在根文件夹中进行修复,并确保在证书路径中具有正确的计算机用户名路径。

Sometime this issue come when we take project from another person or download project from internet and try to run our project then we have issue to run the app.
You can fix this by opening .env.development.local in the root folder and make sure that you have correct computer user name path in certificate path.
spa react app not running

度的依靠╰つ 2025-02-18 08:25:52

您应该删除这些文件,然后运行您的应用程序:

     SSL_CRT_FILE=C:\Users\NameofYourUser\AppData\Roaming\ASP.NET\https\NameOfYourProject.pem
    SSL_KEY_FILE=C:\Users\NameofYourUser\AppData\Roaming\ASP.NET\https\NameOfYourProject.key

you should remove these files and then run your app:

     SSL_CRT_FILE=C:\Users\NameofYourUser\AppData\Roaming\ASP.NET\https\NameOfYourProject.pem
    SSL_KEY_FILE=C:\Users\NameofYourUser\AppData\Roaming\ASP.NET\https\NameOfYourProject.key
爱冒险 2025-02-18 08:25:52

就我而言,以某种方式使用水疗端口的过程变成了僵尸,我没有得到明显的错误。我只是一个“水疗代理还没有准备好。返回临时着陆页”的消息在代理方面。

但是

运行

之后

在 回到能够再次到达水疗中心。

我仅通过在项目文件夹上打开VS代码而始终看到这种行为。没有任何操作,它似乎只是开始在背景上运行水疗中心(?)

In my case, somehow a process that was using the SPA port became a zombie and I was not getting a clear error. I was just a "SPA proxy is not ready. Returning temporary landing page" message on the proxy side.

But after running

Get-Process -Id (Get-NetTCPConnection -LocalPort **port**).OwningProcess

and

taskkill /PID **process id** /F

the proxy went back to being able to reach the SPA again.

I am seeing this behaviour consistently just by opening VS Code on the project folder. Without running anything, it just seems to start running the SPA on the background (?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文