问题背景
在用nodejs写ssr服务的时候,我们服务启动的时候报了这个错误。
经过调查,原来是我们程序有报错了。
但是因为我们在报错之前发送了write请求,导致发送了一半失败了,出发reject,但是reject是发送一个json就会报这个错误了。
try {
res.write(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0, maximum-scale=1.0, user-scalable=no,
viewport-fit=cover">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
<style></style>`);
let html = await renderToString(req);
res.end(html);
} catch (err) {
res.json({
status: -1,
msg: '渲染失败'
});
}
解决办法
把这个res.write放在renderToString之后就行了。