Что-то действительно странное случилось со мной на прошлой неделе. Я получаю одинаковую ошибку во всех проектах при использовании expressjs.
POST http://localhost:8081/clicked net :: ERR_CONNECTION_RESET
Например, в недавнем проекте я пытаюсь сгенерировать документ с помощью модуля officeGen и позволить пользователю загрузить его, когда он нажимает кнопку.
Структура проекта:
публичный / client.js
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
fetch('/clicked', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
публичный / index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Report Generation</title>
</head>
<body>
<h1>Generate Word Document With a click of a button!</h1>
<button id="myButton">Click me!</button>
</body>
<script src="client.js"></script>
</html>
услуги \ generateDocumentService.js
var async = require('async')
const officegen = require('officegen')
var fs = require('fs')
var path = require('path')
var generateDocument = function () { //will search for an exact match
console.log('%c%s', 'color: #f2ceb6', 'INSIDE SERVICE GENERATION DOCUMENT');
//var outDir = path.join(__dirname, '../tmp/')
// var themeXml = fs.readFileSync(path.resolve(__dirname, 'themes/testTheme.xml'), 'utf8')
var docx = officegen({
type: 'docx',
orientation: 'portrait',
pageMargins: {
top: 1000,
left: 1000,
bottom: 1000,
right: 1000
}
// The theme support is NOT working yet...
// themeXml: themeXml
})
// Remove this comment in case of debugging Officegen:
// officegen.setVerboseMode ( true )
docx.on('error', function (err) {
console.log(err)
})
pObj = docx.createP({
align: 'center'
})
pObj.addText(' Report', {
font_face: 'Arial',
font_size: 40
})
//pObj.addLineBreak()
pObj = docx.createP({
backline: 'E0E0E0'
})
pObj.addText('Author: Random Name', {
bold: true
})
pObj = docx.createP({
backline: 'E0E0E0'
})
pObj.addText('Date: 11/06/2019')
pObj = docx.createP({
align: 'center'
})
pObj.addText('Business Process General Information', {
border: 'dotted',
borderSize: 12,
borderColor: '88CCFF',
bold: true
})
var table = [
[{
opts: {
cellColWidth: 4261,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
opts: {
b: true,
align: 'left',
shd: {
fill: '92CDDC',
themeFill: 'text1',
themeFillTint: '80'
},
fontFamily: 'Avenir Book'
}
}
],
['1. What are your main business objectives? ', 'All grown-ups were once children'],
['2. In which sites(Countries) your team is located?', 'there is no harm in putting off a piece of work until another day.'],
[
'3. What are your key business processes? How are they ranked in terms of criticality?',
'4. But when it is a matter of baobabs, that always means a catastrophe.'
],
['5. What are your main interactions with other Business Lines?', 'watch out for the baobabs!']
]
var tableStyle = {
tableColWidth: 4261,
tableSize: 24,
tableColor: 'ada',
tableAlign: 'left',
tableFontFamily: 'Arial',
}
pObj = docx.createTable(table, tableStyle, )
docx.putPageBreak()
var pObj = docx.createP()
pObj.addText('Simple')
pObj.addText(' with color', {
color: '000088'
})
pObj.addText(' and back color.', {
color: '00ffff',
back: '000088'
})
pObj = docx.createP()
pObj.addText('Since ')
pObj.addText('officegen 0.2.12', {
back: '00ffff',
shdType: 'pct12',
shdColor: 'ff0000'
}) // Use pattern in the background.
pObj.addText(' you can do ')
pObj.addText('more cool ', {
highlight: true
}) // Highlight!
pObj.addText('stuff!', {
highlight: 'darkGreen'
}) // Different highlight color.
pObj = docx.createP()
pObj.addText('Even add ')
pObj.addText('external link', {
link: 'https://github.com'
})
pObj.addText('!')
pObj = docx.createP()
pObj.addText('Bold + underline', {
bold: true,
underline: true
})
pObj = docx.createP({
align: 'center'
})
pObj.addText('Center this text', {
border: 'dotted',
borderSize: 12,
borderColor: '88CCFF'
})
pObj = docx.createP()
pObj.options.align = 'right'
pObj.addText('Align this text to the right.')
pObj = docx.createP()
pObj.addText('Those two lines are in the same paragraph,')
pObj.addLineBreak()
pObj.addText('but they are separated by a line break.')
docx.putPageBreak()
pObj = docx.createP()
pObj.addText('Fonts face only.', {
font_face: 'Arial'
})
pObj.addText(' Fonts face and size.', {
font_face: 'Arial',
font_size: 40
})
docx.putPageBreak()
pObj = docx.createP()
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/image3.png'))
docx.putPageBreak()
pObj = docx.createP()
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/image1.png'))
pObj = docx.createP()
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/sword_001.png'))
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/sword_002.png'))
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/sword_003.png'))
//pObj.addText('... some text here ...', { font_face: 'Arial' })
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/sword_004.png'))
pObj = docx.createP()
//pObj.addImage(path.resolve(__dirname, 'images_for_examples/image1.png'))
docx.putPageBreak()
pObj = docx.createListOfNumbers()
pObj.addText('Option 1')
pObj = docx.createListOfNumbers()
pObj.addText('Option 2')
pObj.addHorizontalLine()
pObj = docx.createP({
backline: 'E0E0E0'
})
pObj.addText('Backline text1')
pObj.addText(' text2')
pObj = docx.createP()
pObj.addText('Strikethrough text', {
strikethrough: true
})
pObj.addText('superscript', {
superscript: true
})
pObj.addText('subscript', {
subscript: true
})
var table = [
[{
val: 'No.',
opts: {
cellColWidth: 4261,
b: true,
sz: '48',
shd: {
fill: '7F7F7F',
themeFill: 'text1',
themeFillTint: '80'
},
fontFamily: 'Avenir Book'
}
},
{
val: 'Title1',
opts: {
b: true,
color: 'A00000',
align: 'left',
shd: {
fill: '92CDDC',
themeFill: 'text1',
themeFillTint: '80'
}
}
},
{
val: 'Title2',
opts: {
align: 'left',
cellColWidth: 42,
b: true,
sz: '48',
shd: {
fill: '92CDDC',
themeFill: 'text1',
themeFillTint: '80'
}
}
}
],
[1, 'All grown-ups were once children', ''],
[2, 'there is no harm in putting off a piece of work until another day.', ''],
[
3,
'But when it is a matter of baobabs, that always means a catastrophe.',
''
],
[4, 'watch out for the baobabs!', 'END']
]
var tableStyle = {
tableColWidth: 4261,
tableSize: 24,
tableColor: 'ada',
tableAlign: 'left',
tableFontFamily: 'Comic Sans MS'
}
pObj = docx.createTable(table, tableStyle)
var out = fs.createWriteStream(path.join('Risk Analysis Report.docx'))
out.on('error', function (err) {
console.log(err)
})
async.parallel(
[
function (done) {
out.on('close', function () {
console.log('Finish to create a DOCX file.')
done(null)
})
docx.generate(out)
}
],
function (err) {
if (err) {
console.log('error: ' + err)
} // Endif.
}
)
}
module.exports.generateDocument = generateDocument;
server.js
console.log('Server-side code running');
const express = require('express');
const createDocumentService = require('./services/generateDocumentService.js');
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8081, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
/***http://expressjs.com/en/api.html#res.download */
/**/7915177/zagruzite-fail-s-servera-nodejs-s-pomoschy-express */
/**https://arjunphp.com/download-file-node-js-express-js/ */
/**https://dustinpfister.github.io/2018/06/11/express-response-download/ */
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
// add a document to the DB collection recording the click event
app.post('/clicked', (req, res) => {
const click = {clickTime: new Date()};
console.log(click);
createDocumentService.generateDocument();
setTimeout(() => {
res.download(path.join(__dirname, 'docs/Risk Analysis Report.docx'), function (err) {
console.log(err);
});
}, 500)
});
После запуска приложения:
Когда пользователь нажимает на кнопку, он должен увидеть загружаемый файл отчета благодаря:
В client.js
button.addEventListener('click', function(e) {
console.log('button was clicked');
fetch('/clicked', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
В service.js:
app.post('/clicked', (req, res) => {
const click = {clickTime: new Date()};
console.log(click);
createDocumentService.generateDocument();
setTimeout(() => {
res.download(path.join(__dirname, 'docs/Risk Analysis Report.docx'), function (err) {
console.log(err);
});
}, 500)
});
Однако я получаю обычную ошибку во всех проектах, в которых я использую ExpressJ:
проекты, когда я использую ExpressJS.
POST http://localhost:8081/clicked net :: ERR_CONNECTION_RESET
Это действительно расстраивает. Есть идеи, что может быть причиной этого?
Спасибо!