nodejs unhandled promise rejection when app.post - node.js

When my angular frontend sends post request
order(market: string, price: string, side: string, size: string): Observable<any> {
var payload = { market: market, order: { price: price, side: side, size: size } };
return this.http.post<any>('http://localhost:3000' + "/orders", payload))
.pipe(
tap((res: any) => {
console.log(res);
}),
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}
my nodejs server receives it
app.post('/orders', (req, res) => {
console.log(req.body)
// more code
setTimeout(function () {
axios.post('https://test.com/api/orders', payload, { headers: headers })
.then((response) => {
if (response.status === 201) {
res.sendStatus(201);
} else {
res.sendStatus(400);
}
})
}, 500);
});
I added setTimeout because without it I'm getting Error: Request failed with status code 400.
As a result, I can post an order to test.com/api/orders, but getting promise rejection.
(node:9220) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:9220) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any enhancement i can make here?

Try moving the function content into a try block and catch the errors.
I also recommend to use async await keywords.

Related

Unhandled Promise Rejection Warning Occured

I want to create Product Categories , so i handle it in productController class database call in productCatService class. I added JS promise to this . now it gives following error.
productCatController.js
module.exports.createProductCat = async (request, response)=> {
let result = await productCatService.createProductCat(productCatData);
if (result) {
responseService.successWithData(response, "Product Category Created");
} else {
responseService.errorWithMessage(response, result);
}
}
productCatService.js
module.exports.createProductCat = (productCatData) => {
let productCat = {
name: productCatData.name,
desc: productCatData.desc,
count:productCatData.count,
status : productCatData.status
};
return new Promise((resolve,reject)=>{
ProductCategory.create(productCat).then(result => {
resolve(true);
}).catch(error => {
reject(false)
})
});
}
Error
(node:18808) UnhandledPromiseRejectionWarning: false
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a p
romise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.
html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:18808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a no
n-zero exit code.
Never use await without try/catch. You don't have to try/catch every await, but somewhere down the call stack there needs to be a try/catch block.
You don't need try/catch here, just return the promise from ProductCategory.create()...
// productCatService.js
module.exports.createProductCat = (productCatData) => ProductCategory.create({
name: productCatData.name,
desc: productCatData.desc,
count: productCatData.count,
status: productCatData.status
});
...but you definitely need try/catch here, as this function is the bottom of the stack for this operation, and it is responsible for signifying overall success or failure to the caller.
// productCatController.js
module.exports.createProductCat = async (request, response) => {
try {
await productCatService.createProductCat(productCatData);
responseService.successWithData(response, "Product Category Created");
} catch (err) {
responseService.errorWithMessage(response, err);
}
}
Also don't use new Promise() for operations that already are promises. Keep using the promise you already have. Wrapping new Promise() around existing promises is a source of useless bloat, and it can introduce subtle bugs. Avoid.

node warnings: UnhandledPromiseRejectionWarning: TypeError: displayErrorFunction is not a function

We have two variants of code that both return the same node warnings.
variant 1
import axios from 'axios';
const correctEndpoint = `https://${process.env.AUTH0_DOMAIN}/dbconnections/signup`;
const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: '*/*'
}
};
const registerWithAuth0 = async (payload, redirectFunction, displayErrorFunction) => {
try {
const response = await axios.post(correctEndpoint, payload, headers);
if (response.status === 200) {
redirectFunction();
} else {
displayErrorFunction();
}
} catch (err) {
displayErrorFunction();
}
}
export default registerWithAuth0;
variant 2
import axios from 'axios';
const correctEndpoint = `https://${process.env.AUTH0_DOMAIN}/dbconnections/signup`;
const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: '*/*'
}
};
const registerWithAuth0 = (payload, redirectFunction, displayErrorFunction) => {
axios.post(correctEndpoint, payload, headers)
.then((response) => {
if (response.status === 200) {
redirectFunction();
} else {
displayErrorFunction();
}
})
.catch (() => {
displayErrorFunction();
});
}
export default registerWithAuth0;
all jest tests pass, but we can see some of the following node warnings:
(node:26886) UnhandledPromiseRejectionWarning: TypeError: displayErrorFunction is not a function
(Use `node --trace-warnings ...` to show where the warning was created)
(node:26886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:26886) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:26886) UnhandledPromiseRejectionWarning: TypeError: displayErrorFunction is not a function
(node:26886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
we are using:
node v14.17.1
react v17.0.1
jest v26.6.3
babel-jest v26.6.3
#babel/core v7.14.0
Any ideas about what might be the issue here?
There are some similar issues being reported online, but not quite the same:
UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block
UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
Make sure that any of the test cases is missing that parameter or not.
Alternative you can add a default value for displayErrorFunction.
(payload, redirectFunction, displayErrorFunction = ()=>{} ) => {
}

UnhandledPromiseRejectionWarning: TypeError: res.send is not a function

I am trying to get this aligoapi npm package to work.
when i send request it's showing error
here is my code:
const aligoapi = require('aligoapi');
var AuthData = {
key: '<my_key>',
user_id: '<my_id>',
}
var send = (req, res) => {
console.log('check')
aligoapi.send(req, AuthData)
.then((r) => {
console.log('check1')
res.send(r)
})
.catch((e) => {
console.log('check2')
res.send(e)
})
}
console.log('check3')
var number = {
body: {
sender: '01022558877',
receiver: '01081079508',
msg: 'test msg'
}
}
const result = send(number,'err')
console.log(result)
and this is the terminal output:
justin#Justinui-MacBookPro examples % node test.js
check3
check
undefined
check2
(node:94270) UnhandledPromiseRejectionWarning: TypeError: res.send is not a function
at /Users/justin/Downloads/node.js_exampl/examples/test.js:19:11
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:94270) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:94270) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
justin#Justinui-MacBookPro examples %
here i notice my request isn't actually being sent because it's returning undefined

Retrieving JSON data from an Axios response

I'm using TypeScript to create a Node.js application and I want to retrieve JSON data from an external API. I have a demo version of the code I'm using, can't put my actual codebase up.
private async getData() {
return await Axios.get(
`http://dummy.restapiexample.com/api/v1/employees`
).then(response => {
return response.data;
});
}
getReleaseResults() {
this.getData().then(responseData => {
responseData.data.data.forEach((element: any) => {
console.log(element);
});
});
}
The error message I get is: (node:6068) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at C:\Users\Caoilinn.Hughes\OneDrive\Documents\TypeScript Demos\Azure Test Result Email Extension\emailAzureExtension\app\out\js\apiCaller.js:43:36
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:6068) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6068) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If I don't have the for each and replace it with
console.log(responseData.data.data)
I don't get any issues. FYI the result set has a data property hence the "data.data"
The problem is that you are already returning response.data from your get function and then again you are doing data.data which would not work.
see this. Remove extra data.
getReleaseResults() {
this.getData().then(responseData => {
responseData.data.forEach((element: any) => {
console.log(element);
});
});
}
Add catch block to get the error if there is any. What is the expected response ? try to log it.
return await Axios.get(
`http://dummy.restapiexample.com/api/v1/employees`
).then(response => {
console.log(response);
return response.data;
}).catch(err => console.log(err));

proxyReq.setHeader can not set headers after they are sent

i am building a node.js proxy and i want to add a conditional header
proxy.on('proxyReq', (proxyReq, req, res) => {
const realIP = parseHttpHeader(req.headers['x-real-ip'])[0];
const path = parseHttpHeader(req.headers['x-original-uri'])[0];
pAny([
check_ip(realIP) ,
check_path(path) ,
check_geo(realIP)
]).then(result => {
console.log (result , "result " )
if (result) {
proxyReq.setHeader('namespace' , 'foo');
} else {
proxyReq.setHeader('namespace' , 'bar'); }
console.log('sending req ')
});
});
.
async function check_ip(realIP) {
try {
const result = await ipModel.findOne({ip: realIP}).exec()
console.log(realIP , result , "ip")
if (result) {
return true
} else {
return false
}
} catch (e) {
throw e;
}
}
and it works just fine till i use the methos check_ip then i get the error
(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await
make the check_ip return a promise and try
function check_ip(realIP) {
return ipModel.findOne({ ip: realIP }).exec();
}

Resources