//server app
const express = require('express');
const app = express();
const httpLogger = require('morgan');
const cors = require('cors');
const port = 3000;
app.use(httpLogger('dev'));
app.use(cors()) //see more at https://www.npmjs.com/package/cors
app.use(express.urlencoded({ extended: false }))
app.use(express.json()) //we expect JSON data to be sent as payloads
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.post('/data', (req, res) => {
let data = req.body
console.log('trying to post the following data: ', data)
res.send('Succes')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
});
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
//client app
let url = 'http://127.0.0.1:3000/data'
let data = {}
document
.getElementById('submit')
.addEventListener('click', (event) => {
data.value = document.getElementById('data').value
postData();
event.preventDefault();
});
function postData() {
console.log('trying to send data to server app ', data)
fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data) //data format must be the same as in header
})
.then(res => res.text()
.then(res => console.log(res))
)
}
Winston is a popular logging library in Node.js, widely used to log information, including errors.
const express = require('express');
const app = express();
const winston = require('winston');
// Set up the Winston logger
const logger = winston.createLogger({
level: 'error',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.Console({
format: winston.format.simple(),
}),
],
});
// Example route
app.get('/example/:number', (req, res) => {
try {
const number = parseInt(req.params.number);
console.log(number.toUpperCase()); //intentional error
res.send('Success');
} catch (error) {
const now = new Date(Date.now());
const prettyDate = now.toLocaleString();
logger.error(`${prettyDate}: Error in /example/${req.params.number} route: ${error.message}, the following type: ${error.name}`);
res.status(500).send('Internal Server Error');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
{"level":"error","message":"11/23/2023, 8:35:23 AM: Error in /example/5 route: number.toUpperCase is not a function, the following type: TypeError"}
You can use Winston in combination with other libraries to send emails when errors are logged. Winston itself does not provide direct support for sending emails, but you can use a custom transport or integrate with other libraries like nodemailer to achieve this functionality.
Be cautious with email sending, especially in a high-error environment, to avoid sending too many emails or hitting rate limits of your email provider.
For production use, you might want to add more robust error handling and possibly rate-limiting to the email sending functionality.
Another popular, but more lightweight, error-logging library is Bunyan.
Sentry is an application monitoring and error-tracking platform that helps developers identify, debug, and fix errors in their applications. It captures errors and exceptions that occur in real-time, providing detailed information about the error, including stack traces, environment variables, and user context.
Sentry is related to Winston and Bunyan in that it provides a more sophisticated and centralized approach to logging and error handling. While Winston and Bunyan are primarily focused on logging messages, Sentry specifically focuses on capturing and analyzing errors, providing developers with actionable insights to resolve issues quickly and effectively.