I used nested request by using axios. Initially requesting POST request for the token with key/secrets and then trying to get results in following GET request by using previous request's token.
var config = {
method: 'post',
url: gsecConfig.tokenUrl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function (response) {
if (response.data.access_token) {
const config = {
headers: { Accept: 'application/json', Authorization: `Bearer ${response.data.access_token}` }
};
axios.get(gsecConfig.gsecUrl + gsecid, config)
.then(function (response) {
let supplierData = response.data;
res.status(200).json({
"data": supplierData
});
}).catch(function (error) {
res.status(error.response.status || error.response).json({
"errors": [error.response.data]
});
});
}
})
.catch(function (error) {
res.status(error.response.status || error.response).json({
"errors": [error.response.data]
});
});
while running the application getting below errors.
(node:32) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'status' of undefined
at /whitelist-v1/nodejs/routes/gsec.js:47:39
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:32) 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: 2)
(node:32) [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.
It's highly likely your error doesn't have a .response member, making error.response.status failing. Errors may be decorated with .response only if they originate from the network - the standard Error object doesn't declare it.
So both catches should probably be more like:
res.status(error.response && error.response.status || 500).json({
"errors": [error.response && error.response.data || error.message]
});
If it's not error.response that yields an undefined, then your res is undefined, which should be more obvious to catch.
Related
I have the following function to validate a JSON file:
export const validateJSON = (sourceDir, fileName) => {
return new Promise((resolve, reject) => {
try {
pricingService.processJSON(params, data)
.then(data => {
config.accounts.currencies.forEach(function (currency) {
if (data[currency] === '' || data[currency] === undefined) {
reject({err: 'Missing required values'});
}
});
resolve('JSON Validation Success');
})
.catch(error => {
logger.error({
message: `Error while processing JSON, request Failed with Error: ${error}`,
});
reject({err: error});
});
}
} catch (error) {
logger.error({
message: `Error while validating JSON file, request Failed with Error: ${error}`,
});
return reject({err: {status: 422, message: 'Error while validating JSON - Unprocessable Entity'}});
}
});
};
Now, I have a test in Mocha
it.only('Validate Pricing JSON file', function () {
s3Service.validateJSON('',filename,Date.now()).then(data =>{
setTimeout(() =>{
assert.equal(data, 'JSON Validation Success')
done()
}, 1000)
}).catch(function (error) {
console.error("JSON validation failed "+JSON.stringify(error))
throw error
})
});
What I am trying to do is to validate the JSON file in the test and if there is some fields are missing in the file, the test should fail. Now when I execute the test with a file with missing entries, I am getting the following error printed to console.
JSON validation failed {"err":{"status":422,"message":"Error while validating JSON - Unprocessable Entity"}}
(node:26091) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): #<Object>
(node:26091) [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.
But the test is shown as passed. How can I make it fail if there is an error ? Also how to get rid of the UnhandledPromiseRejectionWarning ? I am very new to Unit Testing and so any help will be appreciated.
Don't throw an error.
Use assert.fail
Check this
I am trying to use the custom headers that is sent from angular, but I could not able to console it in nestJs framework in Node App.
Below are the ways That I am tried to set my headers.
Client Side Code
Try1
let headers = new HttpHeaders();
headers = headers.append("mycustomkey", "value");
headers = headers.append("Content-Type", "text/plain; charset=utf-8");
headers = headers.set(
"Access-Control-Allow-Origin",
"http://localhost:3600"
);
Try2
let headers = new HttpHeaders();
headers.set("Content-Type", "text/plain; charset=utf-8");
headers.set("mycustomkey", "value");
headers.set("Access-Control-Allow-Origin", "http://localhost:3600");
Try3
const headerDict = {
"Content-Type": "text/plain; charset=utf-8",
Accept: "text/plain; charset=utf-8",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Origin": "http://localhost:3600",
"mycustomkey", "value",
};
const requestOptions = {
headers: new HttpHeaders(headerDict),
};
And It is the Post Call, here I included the headers
return this.http
.post(this.URL, data, {
headers: headers,
responseType: "text" as "json",
})
.pipe(
map((response: any) => {
return response;
})
);
Server side Code which is in nestJs, here also I have tried two methods direct headers and req.headers
Try 1
async dycData(#Req() req, #Res() res, #Headers('mycustomkey') mykey:string): Promise<any> {
console.log('It is inside API');
if (req) {
console.log('my key that is setted from the header', mykey);
const rawData = await rawbody(req);
const myData = rawData.toString().trim();
const encryptedString= this.decrypt(myData, mykey)
res.status(200).send(encryptedString);
}
})
Try 2
async dycData(#Req() req, #Res() res, ): Promise<any> {
console.log('It is inside API');
if (req) {
console.log('my key that is setted from the header', req.headers.mycustomkey);
const rawData = await rawbody(req);
const myData = rawData.toString().trim();
const encryptedString= this.decrypt(myData, mycustomkey)
res.status(200).send(encryptedString);
}
})
But it is showing the below error
(node:38432) UnhandledPromiseRejectionWarning: TypeError: Right-hand side of 'instanceof' is not an object at ExpressAdapter.reply (C:\Users\service\node_modules\#nestjs\platform-express\adapters\express-adapter.js:24:18) at ExceptionsHandler.catch (C:\Users\service\node_modules\#nestjs\core\exceptions\base-exception-filter.js:26:24) at ExceptionsHandler.next (C:\Users\Workspace\Angular\service\node_modules\#nestjs\core\exceptions\exceptions-handler.js:16:20) at C:\Users\Workspace\Workspace\Angular\\service\node_modules\#nestjs\core\router\router-proxy.js:13:35 at Layer.handle [as handle_request] (C:\Users\Workspace\Angular\l\service\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Workspace\Angular\service\node_modules\express\lib\router\index.js:317:13) at C:\Users\Workspace\Angular\service\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Workspace\Angular\service\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Workspace\Angular\service\node_modules\express\lib\router\index.js:275:10) at urlencodedParser (C:\Users\Workspace\Angular\service\node_modules\body-parser\lib\types\urlencoded.js:91:7) (node:38432) 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:38432) [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.
pls help to receive the header data from angular app to node app
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 = ()=>{} ) => {
}
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.
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();
}