Sockets or Ajax. What should I use?

What I want

I want to create a login script using Nodejs. I am currently considering using sockets or ajax messages.

What do I have

I installed Nodejs and used this code .

What i tried

I started with a simple Ajax post. I used jQuery for this and I serialized the form. It worked, but sometimes it has some lag or was slow.

So I thought that sockets is the best way to contact the server and return to the client.

Now I am facing a problem that I can’t use anymore serialize()

(heck, I liked this feature serialize()

).

So now I have to use json in my client, getting 2 input values ​​(email and password), creating an object named obj

, add the values ​​and usesocket.emit('login', JSON.stringify(obj, null, 2))

On my server I have

socket.on('login', function(data){
   data = JSON.parse(data)
   if(data.email === 'em@il.com' && data.password === 'secret')
        // return true
   // return false
})

      

Now the problem is that I am unable to tell my client if the credentials are set correctly.

I could do it using another one emit

, but I think it would be an overload.

Can't I use return true

or maybe socket.send(true)

?

Anyone have the same problem? Or maybe a solution to my problem?

Thank!!

+3


source to share


1 answer


Well dude, it smells like this isn't the only function you'll call from your client. Therefore, you should start developing your API.

If you are sending JSON from a client, then the most honorable thing to do from the server is returning JSON. I would use socket.send.

A basic OK answer would look like this:

{ "Status" : true }

      



The main error response will look like this:

{ "Status" : false, "Message": "Login or password not valid" }

      

If in the future you need to return data to your client, then the same base object can be used, you just need to add additional attributes to it and read it on the client.

{ "Status" : true, Data: { /* data here */ } }

      

+3


source







All Articles