The Ajax request keeps encountering a bad request error despite it working perfectly fine in Postman

After spending hours conducting extensive research and trying various methods without success, I am still unable to obtain a JWT token after providing the user and password.

function listenForLogin() {
    console.log('listening')
    $('#submit-btn').on('click', e => {
    e.preventDefault();
    console.log('button-pressed');

    const username = $('#user-input').val().trim();
    const password = $('#pass-input').val().trim();

    var user = {}
    user.username = username;
    user.password = password
    console.log(user);
    $('#user-input').val('');
    $('#pass-input').val('');

    authenticateUser(user);
});
}



//send to autenticate
function authenticateUser(user) {
    console.log('trying to authenticate');
    const settings = {
        url:"/api/auth/login",
        data: JSON.stringify(user),
        dataType: "json",
        method:"POST",
        success: (data) => {
            console.log('authenticated user');
            redirectWithToken(data.authToken, user);
        },
        error: (err) => console.log(err)
    }
    $.ajax(settings);

} 

Despite the server registering a request, I am receiving a 400 status code in response. Below are my defined routes:

'use strict';

const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const {JWT_SECRET, JWT_EXPIRY} = require('dotenv').config();

const router = express.Router();

const createAuthToken = function(user) {

  return jwt.sign({user}, 'shade', {
    subject: user.username,
    expiresIn: '7d',
    algorithm: 'HS256'
  });
};

const localAuth = passport.authenticate('local', {session: false});

router.use(bodyParser.json());

router.post('/login', localAuth, (req, res) => {
  const authToken = createAuthToken(req.user.serialize());
  res.json({authToken});
});

const jwtAuth = passport.authenticate('jwt', {session: false});

router.post('/refresh', jwtAuth, (req, res) => {
    console.log('refresh targeted');
    const authToken = createAuthToken(req.user);
    res.json({authToken});
});

router.get('/dashboard/:user', jwtAuth, (req, res) => {
    res.redirect(`https:flow-state.herokuapp.com/dashboard/${req.params.user}`);
})

module.exports = router; 

I am also struggling to comprehend how

passport.authenticate('localAuth')
functions, so I have included my strategies file for reference.

Update: Upon checking the requests in Fiddler, I am encountering some error messages. Results show a breakdown of response bytes by Content-Type:

RESPONSE BYTES (by Content-Type)

~headers~: 132 ~???????~: 11

If anyone has insights on what this might indicate, I would greatly appreciate the assistance. Thank you!

Answer №1

Did you forget to include the content-type in the ajax settings? Make sure to add contentType: "application/json" in the ajax settings and give it another shot.

Important note :

dataType specifies the type of data expected in the server response.

contentType specifies the type of data that will be sent to the server. The default is: "application/x-www-form-urlencoded"

Answer №2

After struggling for 8 hours and battling a massive headache, a solution finally emerged. Shoutout to @vignz.pie for pointing me in the right direction, although I had to remember to include 'Content-Type': 'application/json' in the headers and stringify the data while setting processData to false to make it work. Grateful for the assistance!

function listenForLogin() {
    console.log('listening')

    $('#submit-btn').on('click', e => {

    e.preventDefault();
    console.log('button-pressed');

    const username = $('#user-input').val().trim();
    const password = $('#pass-input').val().trim();

    $('#user-input').val('');
    $('#pass-input').val('');

    authenticateUser(username, password);

    });
}



//send to autenticate
function authenticateUser(user, pass) {
    var info = {
        username: user,
        password: pass
    };
    console.log(info)
    const settings = {
        url:"/api/auth/login",
        headers: {
            "Content-Type": "application/json" 
        },
        data: JSON.stringify(info),
        processData: false,
        dataType: "json",
        method:"POST",
        success: (data) => {
            console.log('authenticated user');
            redirectWithToken(data.authToken, user);
        },
        error: (err) => console.log(err)
    }
    $.ajax(settings);

}

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

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

Ensure that data is not cached after the page is refreshed at regular intervals of x seconds

In the process of developing a news app, I have implemented a feature where a div with the class .new_feed is refreshed every 10 seconds to fetch new updates. However, I encountered an issue where if a new feed appears in the .new_feed div and is not cli ...

php Stristr() function behaving unexpectedly

I recently came across this code on a coding website and made some modifications to it. However, I'm facing an issue with the stristr() function not behaving as expected. For instance, when I input "E", the output displays "Eva" five times, and when I ...

Clicking multiple times will impede the progress of AJAX requests

My webpage has multiple buttons that can be clicked very quickly, but it seems like Chrome is struggling to keep up with the speed? $(document).ready(function() { $('.favorite-button').unbind('click').click(function() { addLine ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

ReactJs - Reactstrap | Issue with Jumbotron displaying background color

I am trying to create a gray background using Jumbotron in reactstrap. After installation and reference in required places - index.js import 'bootstrap/dist/css/bootstrap.css'; Jumbotron has been implemented in SignIn.js - import Re ...

Guide to setting up jQuery Mobile with bower

For my project, I'm interested in utilizing jquery-mobile through bower. In order to do so, I need to execute npm install and grunt consecutively within the bower_components/jquery-mobile directory to access the minified .js and .css files. This pro ...

Is it possible to upload an image file while the element is hidden with "display: none" property?

I need to upload a file using Selenium webdriver. Here is the URL of the page. <div class="async-upload__thumb item-image__area"> <div class="fab-dialog__thumb-drop-zone async-upload__thumb-drop-zone"> <p class="async-upload__thumb-ms ...

Using forEach to iterate through objects presents challenges when attempting to make changes

What is the reason behind the success of the first modification (when reassigning properties of the object) but the failure of the second modification (when reassigning the whole object)? const arr1 = [ { id: 1, value: 1 }, { id: 2, value: 2 }, ...

What is the process for obtaining the hash of every hyperlink?

I'm currently working on implementing an active link state based on scroll position for each section. My goal is to extract the hash value from the link. The issue I'm facing is that when I run the line 'console.log($(this).eq(i).hash);&ap ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

File input onChange event not triggering after pressing SPACE or ENTER key

My React component features an img tag that allows users to select an image from their computer to display in it. While this component functions correctly on most browsers, I encountered an issue specifically with Chromium based browsers (tested on Chrome, ...

When implementing multer in an express application, I encountered an issue where req.files appeared empty

Currently, I am facing some issues while attempting to upload various file types to the server using multer in an express application. Whenever I make the request, the server responds with a TypeError: req.files is not iterable. Upon investigation, I notic ...

Using Javascript/React to filter an array by a specific value

{ "team_group": ["Alex Smith", "Jake Brown", "Sarah King"], "group_data": { "Alex Smith": { "status": "member" }, "Jake Brown": { "status": &qu ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...