node:internal/errors:477
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:388:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:794:10)
at ServerResponse.contentType (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:624:15)
at ServerResponse.sendStatus (/home/nikita/galaxy-of-hearing/node_modules/express/lib/response.js:373:8)
at /home/nikita/galaxy-of-hearing/index.js:186:13
at Layer.handle [as handle_request] (/home/nikita/galaxy-of-hearing/node_modules/express/lib/router/layer.js:95:5)
at next (/home/nikita/galaxy-of-hearing/node_modules/express/lib/router/route.js:144:13)
at urlencodedParser (/home/nikita/galaxy-of-hearing/node_modules/body-parser/lib/types/urlencoded.js:82:7)
at Layer.handle [as handle_request] (/home/nikita/galaxy-of-hearing/node_modules/express/lib/router/layer.js:95:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Node.js v18.4.0
app.post('/comments', urlencodedParser, async(req, res) => {
const name = req.body.name;
const text = req.body.text;
if (!name || !text) {
res.sendStatus(400)
}
let post = {
name: `${name}`,
text: `${text}`,
} // Структура данных для сервера
let sql = "INSERT INTO comments SET ?" // Writing data to the DB
try {
res.sendStatus(200)
let query = await dbConnection.query(sql, post, err => {});
} catch (err) {
res.sendStatus(500)
}
})
async function postData(url = '', data = {}) {
// Default options are marked with *
const error_text = document.querySelector('p')
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
postData('localhost:3000/comments', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert("Окай");
} else {
alert('С запросом возникла проблема.');
}
}
else {
alert('Загрузка...')
}
}