场景
前端使用 antd pro 的脚手架项目,运行 npm run start
启动 devServer 进行热加载实时打包。
后端使用 koa 来提供 API 接口和中间件,并且使用 HTML 引用前端的打包资源来进行页面渲染。
问题
由于同时起了 devServer 和 node 两个端口服务,所以当我访问后端渲染页面时,umi 中的 socket server 端口指向错误。所以它会不断地重连。
解决方案
修改前端启动命令关闭 socket server:
"start": "npm run clear && cross-env APP_TYPE=site PORT=8899 SOCKET_SERVER=none umi dev",
"start:no-mock": "cross-env MOCK=none PORT=8899 SOCKET_SERVER=none umi dev",
为什么可以这样?
看代码:当 SOCKET_SERVER 为 none 时就不会走 socket server 这一段。
// Connect to WebpackDevServer via a socket.
if (process.env.SOCKET_SERVER !== 'none') {
socket(
process.env.SOCKET_SERVER
? `${stripLastSlash(process.env.SOCKET_SERVER)}/sockjs-node`
: url.format({
protocol: window.location.protocol,
hostname: window.location.hostname,
port: window.location.port,
// Hardcoded in WebpackDevServer
pathname: '/sockjs-node',
}),
{
onclose() {
if (
typeof console !== 'undefined' &&
typeof console.info === 'function'
) {
console.info(
'The development server has disconnected.\nRefresh the page if necessary.',
);
}
},
onmessage(e) {
var message = JSON.parse(e.data);
switch (message.type) {
case 'hash':
handleAvailableHash(message.data);
break;
case 'still-ok':
case 'ok':
handleSuccess();
break;
case 'content-changed':
// Triggered when a file from `contentBase` changed.
window.location.reload();
break;
case 'warnings':
handleWarnings(message.data);
break;
case 'errors':
handleErrors(message.data);
break;
default:
// Do nothing.
}
},
},
);
}
最后
这个问题卡了我好久,所以记录下来希望能帮到别人~