proxyReq.setHeader can not set headers after they are sent - node.js

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();
}

Related

nodejs unhandled promise rejection when app.post

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.

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));

mongoose (check and save if new)

I am getting this error and the request should only be happening once,
UnhandledPromiseRejectionWarning: ParallelSaveError: Can't save() the same doc multiple times in parallel. Document: 5e269bd87c588b6285499c14
at ParallelSaveError.MongooseError [as constructor] (/root/react-passport-example/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at new ParallelSaveError (/root/react-passport-example/node_modules/mongoose/lib/error/parallelSave.js:18:17)
at model.Model.save (/root/react-passport-example/node_modules/mongoose/lib/model.js:434:20)
at /root/react-passport-example/server/routes/public_api.js:64:21
at /root/react-passport-example/node_modules/mongoose/lib/model.js:4590:16
at /root/react-passport-example/node_modules/mongoose/lib/query.js:4351:12
at cb (/root/react-passport-example/node_modules/mongoose/lib/query.js:1900:14)
at result (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:75:17) at executeCallback (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:68:9)
at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at cursor.close (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:36:13) at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at completeClose (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:859:16)
at Cursor.close (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:878:12)
at cursor._next (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:35:25) at self._initializeCursor (/root/react-passport-example/node_modules/mongodb/lib/core/cursor.js:750:9) (node:25221) 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:25221) [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.
I am wondering if there is a better and cleaner way to do the following.
router.post('/login', (req, res) => {
var query = req.body,
add = new LoginModel(query);
console.log(query.email);
LoginModel.find({uid : req.body.uid}, function (err, docs) {
if (docs.length){
console.log(err);
res.status(200).json({
message: "ERROR USER ALREADY EXISIT",
// user values passed through from auth middleware
//user: req.user
});
}else{
add.save(add.save(function (err, query) {
if (err) return console.error(err);
}));
}
});
});
This is happening because you are using add.save twice in your code. Hope below code works for you.
add.save((err, query) => {
if (err) {
return err;
} else {
return result;
}
});

How to handle promise rejection in this case

In here i want to add new field in collection User (User.facebook.botLink)
but i get an error.
Code where i get error looks like this:
app.post('/savelink/', async (req, res, next) => {
try{
console.log("================USER FACEBOOK ===============" + user.local.email)
const {link} = req.body;
console.log(link);
User.update(
{email: user.facebook.email},
{botLink : link},
{multi:true},
function(err, numberAffected){
});
res.status(200).send(link);
}
catch(e){
next(error);
}
});
Error i'm getting:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: error is not defined
(node:6032) [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.
try this
catch(e){
next(error);
}
to
catch(e){
next(e);
}
You can aslo do a try/catch...finally.
Note that the finally block will be executed regardles of the result of try/catch.
For more einformation, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
try{
// some code
}
catch(error){
// handle error
}
finally {
// do something else
}

Resources