NuxtJs login feature is functional, but encounters an unauthorized 401 error

I am utilizing the NuxtJs auth module to manage my authorization within the application state. I have created an express API specifically for this purpose, and it functions correctly.

Below is the configuration included in my nuxt.config.js file:

  axios: {
    baseURL: 'http://localhost:4000/api'
  },

  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
          user: { url: '/users/me', method: 'get', propertyName: 'data' },
        },
      }
    }
  },

Within my login component, I trigger the login route using the following code snippet:

const { data } = await this.$auth.loginWith('local', {
  data: this.login
})

The first call to the /api/users/login route is successful (200), but the subsequent call to /api/users/me results in an error message:

xhr.js:178 GET http://localhost:4000/api/users/me 401 (Unauthorized)

When testing the API endpoint in Postman, I retrieve the user data successfully using the following setup:

> Get - localhost:4000/api/users/me
> 
> Authorization:
> 
> Type: Bearer Token Token: xxxx

Despite the fact that the Nuxt auth module defaults to 'Bearer' type, in my case, it does not function accordingly. While the user login process works as expected, retrieving user data through the second route encounters authorization issues. It's worth noting that the API operates independently from NuxtJS, implemented in a separate project using Express.

Answer №1

Here is a potential solution:

axios: {
baseURL: 'http://localhost:4000/api' },
auth: {
strategies: {
  local: {
    endpoints: {
      login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
      user: { url: '/users/me', method: 'get', propertyName: 'data' },
    },
    tokenType: ''
  }
}

By setting tokenType to an empty string, it can override the default "Bearer" authorization type. This adjustment may be necessary due to certain server configurations leading to a 401 error.

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

Preventing jQuery from loading a div if it already exists: a step-by-step guide

I've encountered an issue with a mock console on my website - every time the same input value is submitted more than once, jQuery reloads the div due to its specific id. Instead of cloning the div, I decided to append a message indicating that it alr ...

Incorporating SQLSRV results into clickable <td> elements: A dynamic approach

As a newcomer to the world of JS/PHP/web development, I'm seeking help with a seemingly simple task. My goal is to make each <td> element in a table clickable, and retrieve the text contained within the clicked <td>. Currently, I have a S ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

Populate an array with the present date and proceed in reverse order

In my code, there is an array that has a specific structure: var graphData = [{ data: [[1, 1300],[2, 1600], [3, 1900], [4, 2100], [5, 2500], [6, 2200], [7, 1800]} I want to replace the numbers in the first element of each sub-array with the corresponding ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

The attempt to convert the value "{ _id: '5d41e769277c0c2ab42d2f8b' }" to an ObjectId was unsuccessful in the "Register" model's "_id" path

Every time I attempt to call findById, an error is thrown, stating that Cast to ObjectId failed for value "{ _id: \' 5d41e769277c0c2ab42d2f8b\' }" at path "_id" for model "Register" I have made multiple changes to my code but still c ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

Tips for utilizing the AngularJS filter to group by two columns in Angular

In my array of objects, each item has three properties: 1. name 2. team 3. age http://jsfiddle.net/HpTDj/46/ I have successfully grouped the items by team, but I am unsure how to group them by both team and age in my current code. I want to display the ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Divide a string into an array starting from the end

I have a unique phrase. var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua"; I am interested in dividing it into chunks of 11 characters starting from the end. Currently, I use: function splitPhrase ...

How can I dynamically assign ng-model with a filter for a particular object in an array?

Is there a recommended method for linking an input element to a specific field of an object in an array using its id? I tried using ng-model along with the find() function from the array prototype. However, the implementation is not working properly as it ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Toggle between bold and original font styles with Javascript buttons

I am looking to create a button that toggles the text in a text area between bold and its previous state. This button should be able to switch back and forth with one click. function toggleTextBold() { var isBold = false; if (isBold) { // Code t ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

Is it possible that when a user is redirected to a different URL, Chrome terminates any pending Ajax requests?

Currently, I have a function that allows the user to unlock a list they are currently editing: function cancelLock(id) { $.ajax({ type: "POST", url: "/ajax.php?action=cancelLock", dataType: 'json', data: "id="+ id }); retur ...

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...