How can I send a custom JSON message to the client using ruby Sinatra?

Question:

How can I send the client a custom json message?

Repl link:
https://replit.com/@totallygoogledrive/authforhh-ruby#index.html

In my main.rb file I have

post '/login' do
  request.body.rewind
  data = JSON.parse(request.body.read)
  username = data['username']

  content_type :json
  { message: 'success' }.to_json
end

This is supposed to log the username, and return the message success to the frontend.

This is what I have in the JS:

document.getElementById('y').innerHTML = response.message;

This takes the json response from the server and puts it into an HTML element.

This is correct code of html

I found out that the server sends back a status code, so using that information I was able to create this in JS that takes the status code and “translates” it into something for the user to see.

if (response.status = 200) {
        alert('success');
      });

This also allows for me to add on more status code responses.

2 Likes

Wait, you want to parse the JSON content received?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.