Email Notification in pm2-health - pm2

I am using pm2-health in NodeJs. It is sending email notification when there are run-time errors. But it is not sending email notifications when facing application level errors.
e.g. If hitting any URL and connection timeout is there, I am catching connection timeout in catch block of axios. Here I need to send email notification.
axios({
url: process.env.ACCESS_TOKEN_API,
proxy: {
protocol: 'http',
host: 'hostname',
port: 8080,
},
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: qs.stringify(params),
timeout: 5000, // 5 seconds timeout
}).then(response => response.data)
.then(data => {
console.log(data);
}).catch(err => {
//Here I want to send email notification
})

you can use something like:
if ( $err ) {
mail('email', 'PM2 Missing', implode("\n", $errored), 'From: email');
}

Related

How to store token in cookies in reactjs frontend on call by login post method to server

this is my login post method in the reactjs frontend
const login = () => {
Axios.post("http://localhost:3001/api/users/login", {
email: values.email,
password: values.password,
}).then((response) => {
console.log(response.data);
}).catch(err =>{
console.log(err)
})
};
this is my expressjs server side, here i have login post method for reactjs frontend, where iam on response i want to send token to set in cookie whenever user post on login method, below is code for login post method
login: (req, res) => {
const body = req.body;
console.log("req.body :", req.body);
getUserByEmail(body.email, (err, results) => {
console.log("results :", results);
if (err) {
console.log(err);
return;
}
if (!results) {
res.json({
status: "failure",
msg: "Invalid email or password",
});
}
const result = compareSync(body.password, results.password);
const SECRET_KEY = "xyz123";
if (result) {
results.password = undefined;
const jsontoken = sign({ result: results }, SECRET_KEY, {
expiresIn: "1h",
});
// console.log(res)
res.cookie("token", jsontoken, {
httpOnly: true,
domain: "http://localhost:3000/login",
});
return res.json({
status: "Success",
msg: "login Successfully",
token: jsontoken,
});
} else {
return res.json({
status: "failure",
msg: "Invalid email or password",
});
}
});
},
What you could do, that is actually more secure, is tell the browser using headers on the response to create a cookie.
There is a header in HTTP called Set-Cookie, which is responsible to do just that, you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie.
The way you add it to your request on express is by calling the res.cookie function on your express request handler. I would suggest telling the cookie to be httpOnly in order for it to not be accessible through JS code, this is just a way to avoid XSS attacks.
Here you have an example to how to achieve that:
res.cookie('token', jsontoken, { httpOnly: true });
Then in order to access the cookie, you would need to use the cookieParser middleware which is responsible in putting all the cookies the client sent in req.cookies.
You use it this way:
app.use(express.cookieParser());

Network Error making post request using Axios

I'm trying to make my application sending a post request and receiving a response using Axios. However i encoutered errors while trying to make a post request.
My code for making post request:
onPostJson = () => {
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi',
{
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
})
.then((response) => {
console.log(response.json());
}, (error) => {
console.log(error);
});
};
Error:
Network Error
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:80:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
I suspected that there is problem with the URL, but i successfully made a post request to this URL using Postman.
Solution: It was syntax error. I forgot to include Header configurations in the code.
onPostJson = () => {
console.log("onpost");
axios.post('http://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
FromDate: "01-Jan-2020",
ToDate: "01-May-2020",
}, {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImtpZW50ZC5haXRzIiwibmJmIjoxNTkzNzY0MDU0LCJleHAiOjE1OTQzNjg4NTQsImlhdCI6MTU5Mzc2NDA1NH0.liIM6g2E_EMXvnRpL1RcU-QVyUAKYxVLZZK05OqZ8Ck',
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(respond => {
// console.log(respond.data.CaThuHoiList);
setShiftData(respond.data.CaThuHoiList);
})
.catch(function (error) {
console.log('Error');
console.log(error);
});
}
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
});
i'm not sure, but ..
Do you want to try it like the code above?

HTTP Post request with credentials and form in nodejs

I want to make an HTTP POST request to a server with credentials (username, password) and content.
More specifically, I used various approaches without success. One of them is:
var request = require('request');
request({
url: 'https://path',
method: 'POST',
auth: {
user: 'username',
pass: 'password'
},
form: {
'grant_type': 'client_credentials',
'text' : 'input-text',
'features': {
'score': true,
}
}
}, function(err, res) {
console.log(res);
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
Do you have any suggestion?
I feel more comfortable using promises. request-promise documentation
var request = require('request-promise');
var options = {
method: 'POST',
url: '',
auth: {
user: '',
password: ''
},
headers: {
'': ''
},
json: true
}
return request(options)
.then(function (response) {
// manipulate response
}).catch(function (err) {
return err
})

Unhandled promise rejection Error: Cannot read property 'json' of undefined

answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
return fetch(BASE_URL + url, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body: JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
}
}
}
})
});
})
I used map function so that on every map it should go to JSON.stringify and assign the values. But I got error "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined". please suggest me any solution.
Thanks in advance.
Here you are creating an array of fetch promises, we need more info about how you handle these promises after that, i suppose you're trying somewhere to get a response from these promises using .then(res => res.json()) but your server response is not in json format.
To handle a fetch promise rejection you need to do this:
fetch(smth)
.catch(error => //handle the error e.g. console.log(error))
To see if there's something wrong in your request json body you can log it server side or log it before sending, you can also log the server response, try this to identify what's wrong:
answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
const body = JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
} }
}
})
console.log('Json body request :', body);
return fetch(BASE_URL + url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body
}).then(res => {
console.log('server response :', res);
return res;
}).catch(err => console.log('Fetch error :', err));
})
I recommend using an app like Postman to test the responses from your api server (easier & faster to debug request/responses from an API)
Edit: I also think you want to do a POST request instead of PUT.

Sailsjs not getting email when using node mailer smtp transport

I am using node mailer to send emails in my sailsjs application.But unable to get emails when using smtp transport to send emails. It is showing the correct response with meesage id in callback method but am not getting email in my mailbox. Here is some configuration I made for smtp transport:
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var transport = nodemailer.createTransport(smtpTransport({
host: 'smtp.hostname.com',
port: 587,
debug: true,
auth: {
user: 'XXXXXX',
pass: 'XXXXXX'
}
}));
And am using following method to send email:
var mailOptions = {
from: 'Sendername <sender#noreply.com>', // sender address
to: reciever#domain.com, // list of receivers
subject: Email Subject, // Subject line
text: 'Hello world ', // plaintext body
};
transport.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Message sent: ' , info);
}
});
And the following response am getting after send email:
Message sent:
{ accepted: [ 'reciever#domain.com' ],
rejected: [],
response: '250 OK id=1XeiXV-00005O-6x',
envelope: { from: 'sender#noreply.com', to: [ 'reciever#domain.com' ] },
messageId: '1413456251972-47ace346-09f25dad-5616cfdb#noreply.com' }
Is your app deployed to a host or are you running it locally? Host's like Modulus often block SMTP ports because of spammers.