我在使用 iisnode 部署在 IIS 服务器上的 React SSR(服务器端渲染)应用程序时遇到问题。该应用程序使用 SSR 在本地运行良好,但当我尝试通过服务器访问它时,出现 500 内部服务器错误。
这是代码的相关部分
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build-server": "webpack --config webpack.server.js",
"test": "react-scripts test",
"eject": "react-scripts eject",
"ssr": "npm run build && npm run build-server && node build-server/main.js"
},
webpack.server.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './server/server.js', // Ensure this path is correct
target: 'node',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'build-server'),
filename: 'main.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
]
}
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
};
网络配置
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="build-server/main.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="DynamicContent">
<match url="/*" />
<action type="Rewrite" url="build-server/main.js" />
</rule>
</rules>
</rewrite>
<iisnode loggingEnabled="true"/>
</system.webServer>
</configuration>
浏览网站网址时出错
我认为问题与您的端口设置有关,我可以像这样重现您的问题(与node.js服务器端口不匹配并且
process.env.PORT
未配置为传递给IIS):
请将其修改为
PORT = process.env.PORT || 3001;
这应该可以解决您的问题。我参考了这篇文章并使用iisnode部署成功: