我有一个使用 aspnet-prerendering 的 .NET Core + React 应用程序。我使用dotnet new reactredux创建了该应用程序。我将它发布到 Azure,并使用 AWS CloudFront 路由到该应用程序。
该应用程序已在所有环境(本地、CI、prestaging...)中运行,但是当我将其部署到生产环境时,它运行了几天,然后我开始遇到很多An attempt was made to access a socket in a way forbidden by its access permissions
错误。当对 POST 进行 POST 时,就会发生这种情况127.0.0.1:<randomPort>
。我没有在我的代码中发布这个 POST,并且我被告知它与如何预渲染 react 有关。这些错误通常仅在部署后大约 1-2 天开始出现。因此,当我第一次部署时,一切看起来都很好,但是当错误开始时,它们会继续出现,直到我在 Azure 中重新部署或重新启动应用程序。
我尝试过的事情:
- 重新启动应用程序可以暂时解决问题。
- 听说这是react hot reloading造成的,所以我确定在Azure中添加了一个appsetting
ASPNETCORE_ENVIRONMENT=Production
:. 这并没有解决问题。 - 我尝试完全注释掉 Startup.cs 的热重载部分以检查这个假设……但在部署该代码 2 天后错误仍然再次出现。
失败与成功的端口示例列表(看似随机......?):
success count_ data
FALSE 3493 http://127.0.0.1:53571
FALSE 1353 http://127.0.0.1:49988
FALSE 535 http://127.0.0.1:55453
FALSE 484 http://127.0.0.1:53144
FALSE 13 http://127.0.0.1:52428
FALSE 7 http://127.0.0.1:49583
TRUE 11247 http://127.0.0.1:56790
TRUE 10960 http://127.0.0.1:55806
TRUE 10920 http://127.0.0.1:55227
TRUE 9300 http://127.0.0.1:55453
TRUE 8472 http://127.0.0.1:51734
TRUE 5602 http://127.0.0.1:53571
TRUE 5429 http://127.0.0.1:56860
代码片段:
启动:
public void ConfigureServices(IServiceCollection services)
{ services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
…
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ReactHotModuleReplacement = true,
// This configuration suppresses the warnings that the server code doesn't match the client code, which happens on reload.
HotModuleReplacementClientOptions = new Dictionary<string, string>()
{
{ "warn", "false" }
}
});
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
…
}
索引.cshtml
@using Microsoft.Extensions.Configuration
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
@inject IConfiguration Configuration
<script>
window.data = @Html.Raw(Json.Serialize(@Model));
</script>
<div id="col-app"
asp-prerender-module="./wwwroot/cost-of-living-calculator/dist/main-server"
asp-prerender-webpack-config="webpack.config.server.js"
asp-prerender-data="@Model">Loading...</div>
@if (hostingEnv.EnvironmentName == "Production")
{
<script src="/cost-of-living-calculator/dist/main.min.js" asp-append-version="true"></script>
}
else
{
<script src="/cost-of-living-calculator/dist/main.js" asp-append-version="true"></script>
}
包.json
...
"aspnet-prerendering": "3.0.1",
"aspnet-webpack": "3.0.0",
"aspnet-webpack-react": "3.0.0",
...
注意:我有一个引导服务器和一个引导客户端,以及一个服务器 webpack 配置和一个客户端 webpack 配置。这是由于对服务器/客户端编译的不同需求。
引导服务器.js
import React from 'react';
import { createServerRenderer } from 'aspnet-prerendering';
import { renderToString } from 'react-dom/server';
import App from './App';
export default createServerRenderer(
params =>
new Promise((resolve, reject) => {
const data = params.data;
const result = renderToString(React.createElement(App, data));
resolve({ html: result });
})
);
引导客户端.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const element = document.getElementById('col-app');
ReactDOM.render(<App {...window.data} />, element);
// This is required to trigger the hot reloading functionality
if (module.hot) {
module.hot.accept('./App', () => {
const NewApp = require('./App').default;
ReactDOM.render(<NewApp {...window.data} />, element);
});
}
Webpack.config.js
var path = require('path');
var webpack = require('webpack');
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';
module.exports = () => {
return {
devtool: 'inline-source-map',
entry: {
'main': ['babel-polyfill', './ClientApp/boot-client.js', './ClientApp/index.scss'],
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
output: {
path: path.join(__dirname, './wwwroot/cost-of-living-calculator/dist'),
publicPath: '/cost-of-living-calculator/dist/',
filename: isDevelopment ? "[name].js" : "[name].min.js"
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
// JavaScript files, which will be transpiled
// based on .babelrc
test: /\.(js|jsx)$/,
exclude: [/node_modules/],
loader: ['babel-loader', 'source-map-loader']
},
{
test: /\.s?css$/,
use: isDevelopment ? [
'style-loader',
'css-loader',
'sass-loader',
] : [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}
]
},
mode: isDevelopment ? 'development' : 'production'
}
};
Webpack.config.server.js
var path = require('path');
const isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';
module.exports = () => {
return {
devtool: 'inline-source-map',
entry: {
'main-server': ['babel-polyfill', './ClientApp/boot-server.js']
},
output: {
path: path.join(__dirname, './wwwroot/cost-of-living-calculator/dist'),
publicPath: '/cost-of-living-calculator/dist/',
filename: "[name].js",
// commonjs is required for server-side compilation
libraryTarget: 'commonjs'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
loader: ['babel-loader', 'source-map-loader']
}
]
},
target: 'node',
mode: isDevelopment ? 'development' : 'production'
}
};
我的问题是 - 为什么会发生这种情况?我该如何预防?