What is the reason behind generating auth.js:65 Uncaught (in promise) TypeError: Unable to access property 'data' of undefined?

Encountering a login issue in my Django application while using Axios and React-Redux. The problem arises when providing incorrect login credentials, resulting in the LOGIN_FAIL action. However, when providing the correct information, the LOGIN_SUCCESS action fails to work and throws the error "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined". This situation has left me puzzled! Interestingly, logging in using Postman works without any issues. How can I resolve this perplexing problem? Any assistance would be greatly appreciated.

Below is my action code:

import axios from "axios";
import {
  errorMessage
} from "./messages";
import {
  USER_LOADING,
  USER_LOADED,
  AUTH_ERROR,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from "./types";

// Login User
export const login = (username, password) => dispatch => {
  // Headers
  const config = {
    headers: {
      "content-type": "application/json"
    }
  }

  // Request body
  const body = JSON.stringify({
    username,
    password
  });

  axios.post("/api/auth/login", body, config)
    .then(res => {
      dispatch({
        action: LOGIN_SUCCESS,
        payload: res.data
      });
    }).catch(err => {
      dispatch(errorMessage(err.response.data, err.response.status));
      dispatch({
        type: LOGIN_FAIL
      });
    });
}

Answer №1

Revise the header "content-type" to read as "Content-Type"

// Headers
  const configuration = {
    headers: {
      "Content-Type": "application/json"
    }

Lastly, adjust "action" to "type" within the axios then block

axios.post("/api/auth/login", body, configuration)
    .then(response => {
      dispatch({
        type: LOGIN_SUCCESS,
        payload: response.data
      });

That concludes the changes needed.

Answer №2

Avoid using JSON.stringify unnecessarily.

const info = {
    name,
    age
};

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

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

Do identical files stored in separate locations produce unique sha1 hashes?

var crypto = require('crypto'); var fs = require('fs'); var file1 = process.argv[2]; var file2 = process.argv[3]; var sha1sum = function(input){ return crypto.createHash('sha1').update(JSON.stringify(input)).digest(' ...

What is the method to showcase every single word?

Can someone help me with my assignment? I am tasked with creating a small user interface that searches a list of words using HTML, CSS, and Javascript. The design is provided, but I need to implement it. I have written the code, but I would like all wor ...

The functionality of opening a link in a new tab is not functioning properly in Internet Explorer

When I use window.open in jQuery to open a link in a new tab, it works perfectly for me in Chrome, Safari, and Firefox. However, I am facing an issue in IE10 where it does not work. $('.div').click(function() { $(this).target = "_blank"; ...

Perform an Ajax request upon clicking on the dropdown list item

I recently created a drop-down list using some JavaScript code. Here's how I did it: <script> $('.menu').dropit(); </script> <ul class="menu"> <li> <a href="#">Product_name</a> ...

Retrieve JSON data generated within a JavaScript-powered webpage

My issue involves two HTML pages: 1) The first HTML Page (page1.html): <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <script type="text/ ...

Error in routing of submit button in Express.js

While attempting to create a basic "to-do list" using HTML requests, I encountered an issue with the PATCH request. Instead of redirecting to "/", it redirected to "/posts/2" and displayed the message "Cannot POST /posts/2", without updating the array elem ...

Scrolling up or down in an HTML webpage using a script

Seeking a code snippet for my website that will allow me to achieve the following functionality: Upon clicking on text_head1, a list of lines should scroll down. Subsequently, when I click on text_head2, the previous list should scroll up while the new l ...

Using jQuery to create a seamless transition in font size as you scroll

Currently, I have a jQuery animation function in place to adjust the font size of the .header-wrap text when the document is scrolled beyond 50px. While this method does work, I am not completely satisfied with it as the transition is not very smooth. Idea ...

Retrieving information from a grandparent view in a child view

I have a scenario with Django models structured like this: class Grandparent(model.Models): grandparent_name = models.CharField(max_length="100") grandparent_age = models.IntegerField(default=10) class Parent(model.Models): parent = Foreign ...

What is the best way to perform a multi-link latency check, display the ping results, and use JavaScript to determine the fastest URL?

click here for image description I have noticed that many websites offer this feature, making it easier for users to choose the best URL or server based on their location. As a JavaScript novice, I'm wondering if someone could demonstrate how this is ...

When the Model popup is activated, it is essential for elements to have an adequate color contrast

Our team is utilizing the axe dev tool for accessibility testing. We encountered an issue where elements behind a model popup (Kendo React model with position: absolute) were displaying insufficient color contrast errors. Upon changing the absolute positio ...

Obtaining a result from a jQuery Ajax call

I am exploring the use of JavaScript in an object-oriented style, and have a method that requires making a remote call to retrieve data for a webpage to function properly. To achieve this, I have created a JavaScript class to handle data retrieval in order ...

Locating conversation within a block of text using Javascript

Is there a way to extract dialogue, the content between quotes, from a paragraph in javascript and save it in an array? var myParagraph = ' “Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?” “Nyquil, ...

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

Leverage the Google Maps JavaScript API v3 to retrieve details for multiple locations using the getDetails(request, callback

I successfully integrated the Google Maps JavaScript API v3 to create a personalized store locator for our company's website. While the current code is functional for two stores, it lacks scalability due to the unconventional methods used. My impleme ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

Exploring the dynamic JSON object from D3 in a Rails view

Currently, I am in the process of learning D3 and my initial attempt involves showcasing a graph where I manually hard-code the json data. To demonstrate this, I have put together a JSFiddle which you can view here: http://jsfiddle.net/Nu95q/1/ The JSFid ...

Exploring the power of Django and S3 for seamless direct uploading capabilities

Within my current project, I have successfully implemented and configured S3 storages. However, I am now in the process of setting up direct uploads to S3 using s3 direct. While most of it is functioning properly - allowing users to upload images directly ...

Tips for keeping mySQL autoincrement stable in Django

In my Django app, I am using AutoFields as primary keys without manually assigning any field in the models. For database management, I have chosen to use mySQL. There is a requirement to periodically export data to Excel or another Django app, so it&apos ...