//server appconstexpress=require('express');constapp=express();consthttpLogger=require('morgan');constcors=require('cors');constport=3000;app.use(httpLogger('dev'));app.use(cors()) //see more at https://www.npmjs.com/package/corsapp.use(express.urlencoded({extended:false}))app.use(express.json()) //we expect JSON data to be sent as payloadsapp.get('/',(req,res)=>{res.send('Hello World!')});// Simple post route exampleapp.post('/data',(req,res)=>{ // destructuringconst{name,email}=req.body;// validates keys exist // bad example: // let data = req.body; // console.log(data.name, data.email);console.log('Posting the following data: ',name,email);res.send('Success');});// Query params exampleapp.get('/greet',(req,res)=>{constname=req.query.name;res.send(`Hello ${name}!`);});// Access: localhost:3000/greet?name=John// route params exampleapp.get('/users/:id',(req,res)=>{constid=req.params.id;res.send(`User ID: ${id}`);});// Access: localhost:3000/users/123app.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.
CORS in 100 seconds
[optional] Route Error Logging Example
Winston is a popular logging library in Node.js, widely used to log information, including errors.
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.
//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))
)
}