0

I'm creating a chat but I was inspired by a source, when I "Log-In" and the chat appears, this appears in the URL:

chat.html?username=rr&room=JavaScript 

How do I make sure that when I enter the chat it simply sees "Chat.html"?

I tried to add this code to it, but the problem would be the same if someone changed, it's like it's a GET. How do I do it in POST? It doesn't come easy with javascript

Code:

const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');

// Get username and room from URL
const { username, room } = Qs.parse(location.search, {
    
  ignoreQueryPrefix: true,
});


const socket = io();

socket.emit('joinRoom', { username, room });

socket.on('roomUsers', ({ room, users }) => {
    outputRoomName(room);
    outputUsers(users);
});


socket.on('message', (message) => {
    console.log(message);
    outputMessage(message);

    chatMessages.scrollTop = chatMessages.scrollHeight;
});

chatForm.addEventListener('submit', (e) => {
    e.preventDefault();

    let msg = e.target.elements.msg.value;

    msg = msg.trim();

    if (!msg) {
        return false;
    }

    socket.emit('chatMessage', msg);
    
    // Clear input
    e.target.elements.msg.value = '';
    e.target.elements.msg.focus();
});

// Output message to DOM
function outputMessage(message) {
    const div = document.createElement('div');
    div.classList.add('message');
    const p = document.createElement('p');
    p.classList.add('meta');
    p.innerText = message.username;
    p.innerHTML += `<span> - ${message.time}</span>`;
    div.appendChild(p);
    const para = document.createElement('p');
    para.classList.add('text');
    para.innerText = message.text;
    div.appendChild(para);
    document.querySelector('.chat-messages').appendChild(div);
}

function outputRoomName(room) {
    roomName.innerText = room;
}

function outputUsers(users) {
    userList.innerHTML = '';
    users.forEach((user) => {
    const li = document.createElement('li');
        li.innerText = user.username;
        userList.appendChild(li);
    });
}

document.getElementById('leave-btn').addEventListener('click', () => {
    const leaveRoom = confirm('Sei sicuro di voler uscire dalla chatroom?');
    if (leaveRoom) {
        window.location = '../index.html';
    } else {
    }
});

I hope I have explained myself well, I just need to add security to the website because then they could enter random "rooms", could I put the sessions?

AloHA_ChiCken
  • 484
  • 1
  • 5
  • 24
  • chat.html?username=rr&room=JavaScript – porcatroia Mar 28 '21 at 20:36
  • At the very least, pls ask google your question before asking us. Google's #1 result: https://stackoverflow.com/questions/1409013/how-to-read-the-post-request-parameters-using-javascript – jgtokyo Mar 29 '21 at 01:56

0 Answers0