简体   繁体   中英

not able to send request to express server using axios

I am building a chat application like whatsapp, & implementing the feature - when user clicks on any person's name, his chats appears, but can't able to send request to server when user clicks

Source code

There is div, when user will click on it, it will fetch data from server (onclick event handler) in Sidebar.js file -

{friends.map((e) => (
                    <div
                        onClick={getChatDetails}
                        key={e.friendName}
                        className='sidebar_chat_info'>
                        <Avatar />
                        <div>
                            <h2>{e.friendName}</h2>
                            <p>{getLastMessage()}</p>
                        </div>
                    </div>
                ))}

this is getChatDetails function in sidebar.js file

const getChatDetails = (e) => {
    //console.log(e.target.textContent);
    const Myfriend = e.target.textContent;
    axios
        .post('http://localhost:2000/message/get', { friend: Myfriend })
        .then((response) => {
            console.log(response);
        })
        .catch((error) => console.log(error));
};

At the server side, this is route in index.js file

Server is running on port 2000

app.post('/message/get', isloggedIn, async (req, res) => {
console.log('REQUESTED!');

try {
    const conversation = await req.user.MyConversation.find(
        (element) => element.friendName == req.body.friend
    );
    const messages = await conversationModel.findById(conversation.chats);
    res.send(messages);
    //await MessageModel.remove({})
} catch (error) {
    res.status(500).send(error);
}
});

This is error on browser console, when I am clicking on div

But when I am sending request through postman, I am getting response

When I am sending request in other files (login.js), it's working there, don't know why it is not working only Sidebar.js file

The issue that you're having is that e in getChatDetails is undefined. The reason for this is is onclick does not pass an event object. In order to pass an event object to your sidebar function, you need to attach an event listener to it, which is a bit better than using onclick in most cases anyways (imo). Something like this:

const sidebar = document.getElementsByClassName('sidebar_chat_info')

for (let i = 0; i < sidebar.length; i++) {
  sidebar[i].addEventListener('click', handleClick = e => {
    //console.log(e.target.textContent);
    const Myfriend = e.target.textContent;
    axios
        .post('http://localhost:2000/message/get', { friend: Myfriend })
        .then((response) => {
            console.log(response);
        })
        .catch((error) => console.log(error));
  })

The middleware "isLoggedIn" causing issue. The problem was in my authentication part, when the user has been logged in then only he will see home page

index.js file at line 113

I added console.log and found that "NOT LOGGED IN " is displayed

function isloggedIn(req, res, next) {
if (req.isAuthenticated()) {
    return next();
} else {
    console.log('NOT LOGGED IN !');
    res.status(500).send('DENIED PERMISSION!');
}
}

I think it is happening because after logging in, I am redirecting to home page from Login.js at line 59

history.push('/', { user: response.data });

const submitForm = async (e) => {
    e.preventDefault();
    axios
        .post('http://localhost:2000/login', {
            username: username,
            password: password,
        })
        .then((response) => {
            history.push('/', { user: response.data });
        })
        .catch((error) => setIsError(true));

    //console.log(user.data); //user.data contains the details
    //CALLING THE HOME PAGE AFTER SIGNUP & SENDING DETAILS OF CURRENT USER THERE !
    //history.push('/', { user: user.data });
};

Maybe the request will be authenticated only from Login.js file, but I can't make other request from this file like getting chats details, sending message etc. I will have to go to home page. That's why I am redirecting to home page after logging in On home page my request is not authenticated.

In postman all routes are working as I am not switching pages.

Login and logout routes are working as they are not taking in account "isLoggedIn"

Please suggest how to work with routes that needs authentication, like send message, gettingchats details?

PS - My request is even not authenticated from Login.js. After logging in, this time I didn't redirect to home page. I made request to route that needs authentication after logging in, it's still showing "NOT LOGGED IN" on server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM