Javascript Cannot read property 'innerText' of null - puppeteer - javascript

Getting this error sometimes while using this function: My function works 2/3 times but I'd like to correct it pls. I'm using puppeteer to navigate and check if my proxy is working.
Cannot set property 'innerText' of null
How to fix it please...
Here's my code.
let proxyValidity = waiting("Checking proxy Validity", 800);
try {
await LOG('Trying to validate IP using an API');
await page.goto(ipValidityUrl, { waitUntil: "load", timeout: 30000 });
} catch (err) {
await LOG('Error occured during loading IP validation API');
await page.close();
await closeBrowser(browser);
stopWaiting(proxyValidity, (stdClrs.FgRed + "ERROR"));
return {
errorId: 3,
msg: 'Unknown Proxy Error',
error: err
};
}
await LOG('IP validation URL loaded');
let proxyInfo = await page.evaluate(() => {
let div = document.querySelector('body > pre');
console.log(div);
jsonObject = JSON.parse(div.innerText);
key = Object.keys(jsonObject);
console.log(jsonObject[key]);
return jsonObject[key];
})
await LOG(`Proxy information recorded: ${proxyInfo}`);
await LOG('Checking for validity of IP');
let isValid = defaultData.proxyAllowedCountries.find((element) => {
return (proxyInfo[0] == element)
}) == proxyInfo[0];
The error code:
UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null
at __puppeteer_evaluation_script__:4:35
[...]

You could add a waitForSelector before calling the evaluate function
await page.waitForSelector('body > pre');
await page.evaluate(...);

Related

forEach not working as expected in NodeJs

I am uploading the excel sheet in DB with the help of Nodejs, I am unable to authenticate and return the error as already exists the userid when the item.USER_ID already exists in DB. my server goes crashes and returns an error as Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Please help in the code how I fix this issue and make it, If the item.USER_ID already exists return error else insert.
var XLSX = require("xlsx");
const fs = require("fs");
try {
const transaction = await con.transaction();
var workbook = XLSX.readFile("myfile.xlsx");
let json_data = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1);
let count = 0;
json_data.map(async (item) => {
let stmt1 = await con.query("SELECT * FROM `table` WHERE `user_id` = :userid", { replacements: { userid: item.USER_ID }, type: con.QueryTypes.SELECT });
if (stmt1.length > 0) {
await transaction.rollback();
return res.json({ message: "already exist the userid" });
} else {
let stmt2 = await con.query("INSERT INTO `table` (`user_id` , `user_name`) VALUES ( :user_id , :user_name)", {
replacements: {
user_id: item.USER_ID,
user_name: item.USER_NAME,
},
type: con.QueryTypes.INSERT,
transaction: transaction,
});
count++;
if (count == json_data.length) {
await transaction.commit();
return res.json({ message: "file uploaded successfully.." });
}
}
});
} catch (err) {
await transaction.rollback();
return res.json({ code: 500, message: { msg: "SQL ERROR" }, error: err.stack, status: "error" });
}
Here in your code, you are calling the res.json({ message: "file uploaded successfully.." }) inside json_data.map function.
since you are calling the res.json function inside an array, it'll be called as many times as of elements present in the array and as we know, we can sent only 1 response at a time for a request.
Because of which you're catching the errors Cannot set headers after they are sent to the client
just remove that res.json inside the map function, add it at the last of that particular map function.
I know you might question for the condition count == json_data.length you added to the code but javascript is async and this particular block can be executed before to that.
Hope this answer helps you! Please comment if you get any errors or have questions.

I am getting TypeError is not a function in nodeJS

I have a login route but whenever it's giving me a typeError not a function. I have checked the code too many times but still can't get why it's giving me this error:
Here's the code:
router.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).send("Please provide an email and password");
}
const user = await User.find({ email });
if (!user) return res.status(401).send("User not found");
const isMatch = await user.checkHashedPassword(password);
if (!isMatch) return res.status(401).send("Invalid credentials");
sendTokenResponse(user, 200, res);
} catch (ex) {
console.log(ex);
}
});
The error I get is that user.checkHashedPassword is not a function.
Here's the checkHashedPassword method in userSchema:
userSchema.methods.checkHashedPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
Here's the complete error that I get:
TypeError: user.checkHashedPassword is not a function
at D:\pythonprogs\todoapp\routes\users.js:46:32
at processTicksAndRejections (internal/process/task_queues.js:93:5)
I have checked the spellings and everything even changed the function name to see if it works but don't know why it's giving this error. Please help
problem is you are using find() method instead of findOne().
find() returns array of collections not object. try this:
const isMatch = await user[0].checkHashedPassword(password)

API Endpoint URL

Basically, the weather API; Apixu changed everything to weatherstack recently, including their endpoints and I need help updating my twitter weather bot.
I did go through the documentation, changed to axios but I keep getting the "Cannot Read Property error"
My Old API Setup
const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');
async function setup(location) {
const options = {
url: "http://api.apixu.com/v1/current.json",
qs: {
key: API_KEY,
q: location
},
json: true
};
let result = await rp(options);
let condition = result.current.condition.text;
let tweetText = `The condition in ${location} is currently ${condition}!`;
console.log("TWEETING : ", tweetText);
sendTweet(tweetText)
}
According to their documentation, this is how it's supposed to be but I keep getting undefined errors.
const params = {
access_key: 'YOUR_ACCESS_KEY',
query: 'New York'
}
axios.get('https://api.weatherstack.com/current', {params})
.then(response => {
const apiResponse = response.data;
console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
}).catch(error => {
console.log(error);
});
The new Base URL: The new API requests start out with :
http://api.weatherstack.com/
documentation : https://weatherstack.com/quickstart
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'c
ondition' of undefined
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)
I would check the response.data.error object, if something goes wrong this will be populated. Funnily enough the http status code is still 200 for some error conditions.
axios.get('https://api.weatherstack.com/current', {params})
.then(response => {
if (!response.data.error) {
const apiResponse = response.data;
console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
} else {
console.log(`Response error: code: ${response.data.error.code}, info: ${response.data.error.info}`)
}
}).catch(error => {
console.error("An error occurred: ", error);
}
);
Using the free tier, I'm getting the following error with this request:
Response error: code: 105, info: Access Restricted - Your current Subscription Plan does not support HTTPS Encryption.
This is easily worked around by changing to http only (This will be less secure!):
axios.get('http://api.weatherstack.com/current', {params})
.then(response => {
if (!response.data.error) {
const apiResponse = response.data;
console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
} else {
console.log(`Response error: code: ${response.data.error.code}, info: ${response.data.error.info}`)
}
}).catch(error => {
console.error("An error occurred: ", error);
}
);
If you are using free version you need to use 'http' to work, i guess if you want to use 'https' it is premiun that you need to buy
Here is the simple example that i have used
http://api.weatherstack.com/current?access_key=0a82bdc4c6628b5f968dd500d30a8857&query=19.0760,-72.8777

Can't solve Fatal Exception:Value for message cannot be cast from ReadableNativeMap to String

I keep getting this error on my react native application. Fatal Exception: java.lang.ClassCastException: Value for message cannot be cast from ReadableNativeMap to String
It does not show up that often. But about %10 of my users gets it.
I thought the problem was from the json. But i'm not sure.
async function getCountry() {
try {
let response = await fetch(
'http://ip-api.com/json/?fields=country',
);
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
let countryName="";
await getCountry().then((data)=> { countryName= data.country}).catch(()=> countryName="")
var user = {
_id : "user:"+email,
name: name,
photo: image,
email: email,
country:countryName
};
I need to fix the crash.

Create an Error object with particular properties in unit testings

I'm trying to implement unit test for the following piece of my code
try {
return await request.post(options);
} catch (err) {
if (err.statusCode === 401) {
log.info('Not authenticated. Refreshing token...');
const tokenResponse =
await Janus.refreshToken(graph.username, graph.password, graph.host, graph.port);
const token = tokenResponse.body.token;
graph.token = token;
return gremlinQuery(graph, query);
}
log.error(`Gremlin script didn't pass : ${err}`);
}
In order to test the lines contained in the catch part, I stub the post function:
stubPost.callsFake(() => Promise.reject(new Error()));
How can I implement an error with the property statusCode? Error constructor is waiting for a string as an input. Can't I pass it an object or something like that?
One way to do this could be as below
MyApiError = function(data) {
this.code = data.code;
this.message = data.message
}
MyApiError.prototype = Error.prototype;
var e = new MyApiError({code: 33, message: 'test'});
e.code; // 33
e.message; // 'test'

Categories

Resources