📕
TIC
  • Tehnologii ale InformaÅ£iei ÅŸi ComunicaÅ£iilor (TIC)
  • Basic web principles
    • How web pages work
    • The pillars of a web page
    • Extra: Getting Started with GitHub
  • Basic HTML
    • Description and Basic Syntax
    • Extra resources
  • Basic CSS
    • Description and Basic Syntax
    • Advanced Positioning
    • Extra Resources
  • Basic Javascript
    • Description and basic syntax
    • The Document Object Model
    • Extra Resources
    • Basic assignment
    • The Color Game
  • Advanced Javascript
    • Runtime Engine, Callstack, Scope
    • ES6
  • Advanced Javascript 2
  • Programming paradigms
  • OOP Javascript
  • Functional Programming
  • OOP vs. Functional Programming
  • Asynchronous Javascript
  • Backend Javascript
    • NodeJS
    • ExpressJS
    • REST APIs
    • Authentication and Authorization
  • Firebase
    • NoSQL Databases
    • Database as a Service
    • Google Cloud Firestore
    • CRUD operations
    • Securing your database
  • Basic VueJS
  • Agenda: VueJS and Frontend Frameworks
  • Single Page Applications
  • VueJS basic syntax
  • Vue Components
  • Advanced VueJS
  • Advanced apps with Vue CLI
  • Vue Router
  • SPA State Management - Vuex
  • Composition API
  • Evaluation
    • Final Individual assignment
Powered by GitBook
On this page
  • POST example
  • [optional] Route Error Logging Example

Was this helpful?

  1. Backend Javascript

ExpressJS

POST example

//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))
      )
  }
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Post Example</title>
</head>

<body>
  <h1>TIC</h1>
  <p>Send some data</p>
  <form>
      <input type="text" placeholder="data to be sent" id="data">
      <button id="submit">Send Data</button>
  </form>
  <script src="js/script.js"></script>
</body>
</html>

[optional] Route Error Logging Example

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.

PreviousNodeJSNextREST APIs

Last updated 1 year ago

Was this helpful?

After accessing the following URL: the content of the error.log file should look like this:

http://localhost:3000/example/5
CORS in 100 seconds