Unauthenticated request with Ajax triggered a 401 error response from the back-end while

I encountered an issue while working with AJAX. Through Insomnia, I managed to receive a successful response code of 200 by using the API token.

However, upon implementing the same code in HTML, I faced a frustrating 401 error message indicating access denied.

$.ajax({
  url: "https://ecoexchange.dscloud.me:8080/api/get",
  method: "GET",
  apikey: sessionStorage.getItem("apikey"),
  dataType: 'json',
  success: function(result) {
    $('#infoTable tr').empty();
    var header = $('#infoTable thead');
    var body = $('#infoTable tbody');
    var hTr;
    $('#infoTable thead').append(hTr = $('<tr>'));
    // Headers
    for (var h = 0; h < result.headers.length; h++) {
      hTr.append($('<th>', {
        text: result.headers[h]
      }))
    }
    // Body
    for (var d in result.data) {
      var data = result.data[d];
      $('#infoTable tbody').append($('<tr>')
        .append($('<td>', {
          text: data.RecyclableID
        }))
        .append($('<td>', {
          text: data.Name
        }))
        .append($('<td>', {
          text: data.RecyclableType
        }))
      )
    }
  }
})

I am struggling to figure out how to properly authenticate with the token or incorporate a username and password.

What steps can I take to enhance the code and avoid encountering this error?

Answer №1

Can you explain what the significance of the apikey parameter is in your code? I couldn't find any mention of it in the official documentation.

apikey: sessionStorage.getItem("apikey"),

Were you intending to send it as a header instead? For instance:

headers: {"apikey": sessionStorage.getItem("apikey")},

The guidelines for integrating the API key should be outlined in the service's documentation. You seem to have that information, considering:

I managed to successfully access the service using Insomnia

You will need to specify where to include the value in your AJAX request. It is likely to be either as a header or a query string value. Keep in mind that the jQuery .ajax() function won't automatically handle this, so you must define it.

Answer №2

To resolve the issue you are encountering with passing queries, I recommend checking out this solution on Stack Overflow.

As mentioned in David's response, it is crucial to identify whether your apikey needs to be included in the headers or parameters on the server-side.

If the apikey should be sent as a query parameter according to your documentation, you can implement the following code snippet:

$.get('/api/get' , {'apikey' : 'YOUR-KEY'}).done((res) => {
     console.log(res) 
})

Alternatively, if the apikey needs to be included in the headers, you can use the following approach:

$.ajax({

        url: '/api/get',
        type: 'GET',
        headers: {'apikey': 'YOUR-KEY'},
        success: (res) =>{
            console.log(res);
        }

})

For more information on using jQuery.ajax(), refer to the official documentation.

You can also explore the documentation for jQuery.get() here.

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

The occurrence of DI within the directive leads to an unfamiliar providerProvider

From my understanding, AngularJS automatically appends "Provider" to registered providers, so it's not necessary to include it in the name when calling them. However, I'm following this convention and still encountering an issue where the console ...

Setting a custom expiration time for a custom token in Firebase authentication

Using the firebase custom auth, I have created a custom token. I am looking for a way to customize and update this token by shortening its expiry time based on when a session finishes. For example, if a session ends after 20 seconds or 5 minutes, I want to ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

How come my form submission continues to refresh the page?

I am new to the world of ajax and have a basic understanding of jQuery. Nonetheless, I am facing challenges while testing a simple ajax script. I have gone through similar questions for help, but unfortunately, I haven't been able to find a solution y ...

How can I limit the impact of range with jQuery?

<table> ... </table> <script type="text/javascript"> $(selecctor).click(...) </script> The content above is meant to be dynamically loaded using ajax. My objective is to limit the scope of the selector so that it only impacts the ...

The request to http://localhost:7500/api/users/posts has resulted in a 400 error response indicating a Bad

Currently, I am in the process of saving data to a MongoDB database using Axios. I have set up a form for users to fill out and upon clicking the save button, the data should be stored. This is how my code looks: import auction1 from '../../Imag ...

The Express app.post endpoint is not acknowledging incoming POST requests from Postman

I am facing an issue where my POST request using Postman to my express app is timing out. Here is the request: https://i.sstatic.net/UfL07.png And here is the app: import express from 'express' import bodyParser from 'body-parser' i ...

Utilizing percentages in Jquery operations

For my website with a fluid layout, I am using percentages in my Jquery sizes and animations. The issue I encountered is that Jquery does not comprehend percentages. Here's an example of what I need: The <body> element is 100% wide. <articl ...

Refreshing express-session sessions

My goal is to enhance the user experience by retrieving their profile from the mongodb database when they visit the page, and then updating their session with this information. Currently, I am utilizing the following packages for managing sessions: - ex ...

Reorganizing and arranging Ajax data using jQuery

My data consists of two dimensions: purchases and referral references. Orders are generated with PDO and pulled from a MySQL database: <div rfrnc="joe" id="1" class="order"><div>1 Laptop $220</div><div cla ...

Tips for implementing a confirmation dialogue box prior to submitting a form:

As a new developer, I am facing an issue that I believe you can help me with. I want to display a confirmation box before deleting. How can I achieve this in my Ajax code? HTML: <input type='button' class="btn btn-danger delete_button" id="de ...

Displaying spherical objects (or individual points) within a particle network

In my project, I am utilizing the Three.JS library to showcase a point cloud on a web browser. The point cloud is created once at the beginning and remains static with no additional points being added or removed. However, it does require functionality for ...

Create a video player in your HTML code using the class "afterglow", and also link a separate class to it for additional styling

I'm encountering some challenges with a project that involves a JS file for a Bootstrap modal popup and an HTML5 video player. The issue I'm facing is that I am unable to link the class for the video player theme. Can anyone here assist me in ide ...

Does the modal popup extender change the screen size?

I need help understanding if this behavior is normal. I have a well-designed asp.net site with all content fitting on one page without the need for scrolling. However, when a specific button is clicked to show additional content using modalpopupextender, t ...

I am looking to display an image as a value in the dropdown menu of my Contact Form 7 on my WordPress website

I am currently working on a Wordpress website where I have a page showcasing 50 different company logos. Below the logo section, there is a form created using Contact Form 7. The logo section was built using a combination of HTML and CSS. Within the form ...

What is the best method for organizing an array of objects based on their subobjects?

When developing a web app's back-end with TypeScript, I've found intersection types to be incredibly beneficial for optimizing SQL queries. Imagine having the following tables: User userId: number userEmail: string Post postId: number userId: ...

The rendering in index.js with ReactDOM.render is not working for my app and is throwing an error stating:

Issue: Unexpected object received instead of a string or a class/function in the Context.Consumer render method. Despite not using Context in my application, and with no errors showing in Visual Studio console, I encountered this issue. index.js import ...

"Using a separate JavaScript file in NodeJS without the 'require' defined will result

Apologies if this question seems basic, but I am new to NodeJS and have been struggling with this issue. I have installed requireJS using the command: npm install requirejs I used express project to set up the project directory structure as follows: ...

Stuck on an endless loop of the Ionic splash screen

Currently, I am facing an issue with my Ionic 1 project. Everything was functioning properly until a few days ago when the splash screen stopped disappearing on iOS, although it still does on Android. I have searched for solutions on Google but haven' ...

The filter() method in Jquery does not function properly when used with a class

Seeking guidance as a beginner web developer. Encountering an issue with the filter() function. When using it with an ID selector like ('#test'), everything works smoothly. However, when attempting to apply it to a class selector like ('.loc ...