I have been working on extracting two keywords from a URL in the following format:
localhost:3000/"charactername"/"realmname"
My goal is to extract "charactername" and "realmname" and assign them to variables.
Here is the code snippet I am using:
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname = req.url.split("/")[2];
console.log(realmname);
Initially, everything works smoothly. However, I noticed that when a request is made for a "favicon.ico", my variables become undefined due to a new request URL being generated. To address this issue, I tried wrapping the code snippet in an if statement like this:
if(req.url !== '/favicon.ico'){
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname = req.url.split("/")[2];
console.log(realmname);
}
Although the console logs show that the variables are correctly set to their values without being undefined, as the next part of the code executes:
if(charactername.length > 0){
res.writeHead(200, {'Content-Type': 'text/html'});
renderer.view("header", {}, res);
//get json from battle.net
var characterProfile = new Profile(charactername, realmname);
//on "end"
characterProfile.on("end", function(profileJSON){
//Show profile
//Store values we need
var values = {
avatarURL: profileJSON.thumbnail,
charactername: profileJSON.name,
realmname: profileJSON.realm,
level: profileJSON.level
}
//Simple response
renderer.view("profile", values, res);
renderer.view("footer", {}, res);
res.end();
});
An error occurs stating that it cannot read property length of undefined. This suggests that the variables somehow become undefined regardless. Can someone provide guidance on how to tackle this issue?