When I try to create a chatroom on my chat app, it fails to do so and throws an error. I check the logs and it says:
Chat running on port 3000
undefined
undefined
file:///app/server.js:149
data[user].chatrooms.push(id);
^
TypeError: Cannot read property 'chatrooms' of undefined
at file:///app/server.js:149:22
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:71:3)
The two undefined
in the logs are an attempt to console.log
the user and the user object from the users.json
file, which both return undefined
. Therefore, because data[user]
is undefined
, it fails to successfully create the chatroom, and the chatroom is only partially created.
I am pretty sure I have checked if the user’s SID is valid in public/home.js
, and also passed all the required body parameters to /api/create-chatroom
. So what’s going on?
server.js
app.post("/api/create-chatroom", jsonParser, (req, res) => {
const id = randomUUID();
let user = sessions[req.body.sid];
let jsonData = {
id,
name: req.body.name,
messages: [],
owner: user
};
fs.writeFile(`chatrooms/${id}.json`, JSON.stringify(jsonData), (err) => {
if(err) {
res.json({ success: false, error: err });
} else {
fs.readFile("users.json", "utf8", (erro, data) => {
if(erro) {
res.json({ success: false, error: erro });
} else {
data = JSON.parse(data);
console.log(user)
console.log(data[user])
data[user].chatrooms.push(id);
fs.writeFile("users.json", JSON.stringify(data), (error) => {
if(error) {
res.json({ success: false, error });
} else {
res.json({ success: true, id });
}
});
}
});
}
});
});
public/home.js
function parseCookies() {
let cookieStr = document.cookie.split(";");
let cookies = {};
for(let i = 0; i < cookieStr.length; i++) {
cookieStr[i] = cookieStr[i].split("=");
cookies[cookieStr[i][0]] = cookieStr[i][1];
}
return cookies;
}
async function checkSid() {
let sid;
if("sid" in parseCookies()) {
let res = await fetch(`/api/sid-exists?sid=${parseCookies().sid}`);
res = await res.json();
if(res.exists) {
sid = parseCookies().sid;
} else {
location.href = "/login";
}
} else {
location.href = "/login";
}
return sid;
}
const sid = checkSid();
/*************************/
function createChatroomModal() {
document.getElementById("modal-content").innerHTML = `
<center>
<h1>Create a chatroom</h1>
<label for="name">Name:</label>
<input name="name" id="name" /><br/>
<button style="margin:5px;" onclick="createChatroom();">Create</button>
</center>
`;
document.getElementById("modal").style.display = "block";
}
async function createChatroom() {
let res = await fetch("/api/create-chatroom", {
method: "POST",
body: {
name: document.getElementById("name"),
sid
}
});
res = await res.json();
if("error" in res) {
if(res.error == "Invalid SID") {
location.href = "/login"
}
}
}