Ways to verify email registration using API

app.js

client.request
      .get(
        'https://url.dev/api/users/${email}',
        options
      )
      .then(
        data => {
          const userInfo = JSON.parse(data.response).data
          if (data.ok) {
            var name = userInfo.name;
            var initials = name.charAt(0);
            document.getElementById("nameInitial").innerHTML = initials;
            document.getElementById("name").innerHTML = name;
            document.getElementById("email").innerHTML = userInfo.email;
           }
          else {
            var name = "Unknown";
            var initials = name.charAt(0);
            document.getElementById("nameInitial").innerHTML = initials;
            document.getElementById("name").innerHTML = name;
            document.getElementById("email").innerHTML = "Unknown"
          }
          
        },
          error => {
            console.error('An error occurred during the request..');
            console.error(error);
          }
      );

My goal is to handle errors when attempting to fetch user information by email. If the email is not registered, a 404 status code will be returned, but for some reason, the display logic in the else block does not work as expected.

The console.log(data.ok) shows a response code of 200 when an existing email is used, but returns the following when an unregistered email is used:

Object
attempts: 1
errorSource: "APP"
headers: {date: "Tue, 19 Apr 2021 05:41:27 GMT", content-type: "application/json", transfer-encoding: "chunked", connection: "close", set-cookie: Array(1), …}
response: "{\n    \"message\": \"\"\n}"
status: 404

I am unsure why the desired output is not achieved when an unregistered email is used and the response code is 404.

Answer №1

Explanation of operation: If a GET request URL is present, the response will be 200 OK. If a GET request URL is not found, the response will be 404 not found. In cases where your name is not registered and the associated URL does not exist, the program will skip the else block and trigger the error block instead. Personal suggestion: I recommend redesigning the API to include the name as a parameter for better functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the mouse hovers over a specific area, a sIFR element

Here is the html code that I am working with: <li><a href="#"><span class="font Berthold-light">1</span>Consectetur adipiscing elit risus.</a></li> I have successfully replaced the number within the span using sIFR. Ho ...

Invisibility of form data on new page - PHP and Javascript

I have a webpage with multiple hyperlinks. Each hyperlink should redirect the user to a new page with the URL sent as POST data. What I can do: 1. Open the new page successfully. The issue I'm facing: 1. On the new page, I cannot access the URL ...

Deciphering unique characters within JSON syntax

I am currently using NSJSONSerialization to parse JSON data. NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"url"]]; NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMu ...

Tips for confirming a website URL using jquery

Looking for help with this form issue: Trying to identify if a valid web address is entered in the input field <form onsubmit='return formValidation()'> <p id="p4"></p> <label>Address:</label> ...

Is it possible to push FormData using JQuery?

Can additional data be included in a FormData object used for file uploads, given that FormData does not support .push()? $("frm").submit(function (e) { e.preventDefault(); var data = new FormData($(this)[0]); }); ...

Add data to a DataTable without the need to manually refresh the page

I am looking to dynamically append a DataTable on my webpage. The goal is to have a form that users can fill out multiple times and each time they submit their inputs, the results will be added to the DataTable for display. <table id="table" class="di ...

How to retrieve the object's property with the highest numerical value using JavaScript

My current object is structured as follows: const obj = { happy: 0.6, neutral: 0.1, said: 0.3 } I'm trying to determine the best method to retrieve the property with the highest value (in this case, it would be "happy"). Any suggestions o ...

Toggle the visibility of elements (such as a form) with a click of a link - Utilize ajax to

I'm attempting to use jQuery to toggle the visibility of a form. This functionality is triggered by clicking on a specific link... The goal is to hide all links with data-action="edit" and only display the form that follows the clicked link, as there ...

Learn the simple process of resetting a form with the input type reset functionality

Hello! This is my first time asking a question here, so please bear with me if I make any mistakes. I am attempting to reset a form using the input type=reset tag in HTML5, but I'm encountering some issues. I've included a snippet of my code bel ...

Sweetalert not functioning properly when deleting records from Datatable

I am currently working on a CRM script and encountering an issue. The customers are stored in a data table, and I am trying to implement a delete function with confirmation from both the database and the data table. I have written some code and placed it w ...

Ways to remove curly brackets from a dictionary?

Is there a way to remove the curly brackets (with ** around them) from my JSON response without messing up the entire Dictionary? If not, is it possible to assign key-values before the curly brackets (with ** around them) to access the values in the card k ...

Sophisticated sinatra parameter

Creating Dynamic Surveys <script type="text/x-jsrender" id="surveyTemplate"> <li class="question"> <input type="text" name="survey[question]" /> <button class="add_answer">Add Answer</button> <ul> ...

Having trouble accessing an item within my JSON response

I'm using xml2js to parse my XML data and access the values. However, I'm facing some challenges while trying to retrieve the GetProvidersResponse and iterating through GetProvidersResult and Providers. How can I successfully access these items? ...

Remove HTML tags from user-editable content

I need to save contenteditable data into a JavaScript array, with each new line being a separate array item. Initially, I cleared out Chrome's HTML like this: html = html //empty line looks like this: .replace(/<div><br\s*[\/]?> ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

How can we use Node.js and Express to create routes with functions that accept multiple parameters?

When it comes to Express routes, I often come across different formats and have some questions about passing multiple parameters to app.get(). I am familiar with the standard usage involving a callback function like function(req, res), but I am confused a ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

What could be causing the server to not successfully receive the ajax request?

I need to conduct integration tests on a website that routes all requests through a proxy: var express = require("express"), http = require("http"), port = (process.env.PORT || 8001), server = module.exports = express(), httpProxy = requir ...

Invalid element type detected. A string was expected, but instead found undefined

Following a recent update of next-auth, an unexpected error has surfaced: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your compon ...

Modify the class of an a-element using JavaScript

I'm not very experienced with Javascript, and I've encountered a frustrating issue. My problem arises from having a list that contains other lists. I have a script that toggles the visibility of these lists on click. However, I also want to togg ...