Unusual actions observed during the submission of a post request in Angular 2

After starting a new application and implementing JWT for authentication, I encountered an unusual issue. The login button sends the request differently across different browsers. In Chrome and Firefox, it sends the request without the body, while in Edge, it submits twice - first without the body, then a second time immediately after with the body intact.

To troubleshoot, I hardcoded the login credentials directly into the post request to simplify the process.

The following code snippets illustrate the header component implementation:

<ul id="links">
    <li>
        <a href="/">Home</a>
    </li>
    <li>
        <a href="/census">Census</a>
    </li>
    <li>
        <button (click)="login()">Login</button>
    </li>
</ul>

Here is the corresponding TypeScript code snippet:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthenticationService } from '../_services/Authentication.Service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor(private _auth: AuthenticationService, private router: Router) { }

  ngOnInit() {
  }

  login() {
        this.loading = true;
        this._auth.login(this.model.username, this.model.password)
            .subscribe(result => {

            });
    }

}

And here is the Authentication Service implementation:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
 
@Injectable()
export class AuthenticationService {
    public token: string;
 
    constructor(private http: Http) {
        // set token if saved in local storage
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }
 
    login(usn: string, psw: string): Observable<boolean> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post('http://localhost:5000/auth', JSON.stringify({ username: "email-removed", password: "password-removed" }), options)
                    .map((response: Response) => { return true; });
    }
}

This issue becomes more evident when examining the network requests in different browsers. Here is a comparison between Chrome and Edge:

Request URL: http://localhost:5000/auth
Request Method: OPTIONS
Status Code: 200 OK

[Chrome Request Details]
...Details of the empty response...

[Edge Request Details]
POST http://localhost:5000/auth HTTP/1.1
Accept: */*
content-type: application/json
...Details of the correct response containing access_token...

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...."
}

An interesting observation is that the backend is a Python/Flask rest. Requests marked as OPTIONS are seen as empty, while those labeled as POST contain the necessary data, as visible in the responses received.

Answer №1

Ensure that the route you are calling has a trailing slash at the end. For example, instead of requesting

'http://localhost:5000/auth'

you should request

'http://localhost:5000/auth/'

I hope this tip is beneficial to you.

Answer №2

Seems like you're encountering difficulties with a cross-origin request.
The host of the page (localhost:4200) differs from the destination (localhost:5000).

In such cases, Chrome initiates a preflighted request:

Unlike simple requests (mentioned earlier), "preflighted" requests first send an HTTP request using the OPTIONS method to validate if the actual request can be sent safely. Cross-site requests undergo this preflight process due to potential impacts on user data.

The response received from the server lacks the necessary CORS headers, resulting in Chrome withholding the actual POST request.

Answer №3

One solution for dealing with Chrome preflighted requests is to utilize a Chrome extension that allows you to enable CORS. By installing this specific extension, you can add the necessary header '*Allow-Control-Allow-Origin: ' to your headers. This method has proven successful in my experience when working with django on localhost:8000 and angular2 on localhost:4200.

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

Experiencing unexpected behavior with Next.JS getStaticProps functionality

I am currently working on a website where I want to display dynamic feedback as cards. However, my fetchData variable within the Home function is always returning undefined. Here's the code snippet I have tried: import UserCard from "../component ...

Is it necessary to assign angular.module to a variable in AngularJS?

After reviewing two AngularJS examples on Github, I find myself uncertain about how to properly modularize controllers. The first example sets a variable (foodMeApp) and reuses it, resulting in controllers that require fewer arguments and are easier to rea ...

What is the best way to ensure consistency in a value across various browsers using Javascript?

I am currently developing a feature on a webpage that displays the last update date of the page. The functionality I am aiming for is to select a date in the first input box, click the update button, and have the second box populate the Last Updated field ...

Function not being called by JQuery selector

Having an issue with a specific Jquery selector. $("#confirmEmailInput").change(function() { validate() confirmEmail() }); The current selector I'm using is shown above. My goal is to have the functions called upon a change in ...

Elements positioned next to each other with no margin when spread across multiple lines

I have a color picker with a right margin of 6px. https://i.sstatic.net/OHqQK.png I need the white square (with the black check marker) to not have a right margin so it doesn't wrap to the next line and can use the full width. Instead of applyin ...

My code seems to be malfunctioning

I'm attempting to conceal the chatname div. Once hidden, I want to position the chatid at the bottom, which is why the value 64px is utilized. However, I encountered an error stating The function toggle3(); has not been defined. <div id="chat ...

Do Angular module chunk files include imported modules?

Just imagine, you have X,Y,Z lazy loaded modules in your Angular application. Now, envision that all of those modules need to utilize a 3rd party module that is approximately 1MB in size. As a result, you will include imports: [ ... OurHeavyModule] in all ...

Display a button in ngx-datatable on mouse hover in Angular 9

My goal is to display a link on mouseover of the corresponding cell in ngx-datatable. However, the link appears on all rows within that column instead. Below is the code I am currently using: <ngx-datatable class="material ml-0 mr-0" [r ...

adjusting the font color based on the currently selected tab

After seeking help for my previous question on Unable to add a background colour to the button in navigation I have successfully resolved that issue and continued working, but now I am facing a new challenge. I need to change the font color of the navigat ...

Guide for reading several csv files with node.js in a folder?

I've been struggling to read multiple CSV files from a directory and store them in a database. Despite finding some code that scans the file names, it doesn't actually return the files themselves. I'm hoping someone can help me tweak this co ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

Angular 5 Custom validators: Error message - 'passwordG' is not defined in ng

Currently working with Angular 5 and attempting to create custom validators for password inputs along with a confirmation password field. This is the HTML code : <div formGroupName = "passwordG"> <div class="form-group"> <label ...

Strategies for triggering a function once two separate events have finished executing

I am trying to implement the cropper plugin within a modal pop-up. The goal is to display an image in the popup when the user clicks on the image uploader, and then initialize the cropper plugin once the modal pop-up has finished its show animation and the ...

Events in Three.js have an impact on the Document Object Model (

Here's a simple question for you. Is it possible to create click events in a three.js scene that can manipulate the DOM? For example, if an object is clicked in the scene, can it make a panel outside the scene become visible? Thank you! ...

Tips for modifying the hue of the hint attribute within vue.js?

`<v-text-field id="loginPasswordId" ref="password" v-model="password" class="login-input" dense :disabled="loading" :hint="hello world" :loading="loading" maxlength= ...

JavaScript string representing the actual value of a string

In order to reliably extract string literals from a JavaScript string, I need to create a function, let's name it f. Here are some examples: f('hello world') //-> 'hello world' (or "hello world") f('hello "world"') / ...

Anticipate the absence of a specific object length

I have an Object that I need to test for null: getLastTeamUpdatedItemLogBuffer(): IBufferElement { const storageItems = this.storageSvc.getItem(StorageKey.lastTeamUpdatedItem, true) as IBufferElement; return storageItems || null; } This is the IBufferE ...

Having trouble getting Edge browser to identify embedded blob as a valid source URL within a video tag

Having trouble using a blob as the source for a video file. Works well on Chrome and Safari, but facing issues on Edge. This code is written in TypeScript with Angular 7. On Edge mobile, it seems like a broken link is displayed. private initVideoFromBlo ...

The function fs.reddirSync does not exist and is causing a TypeError

I am having trouble with this code and not quite sure where the issue lies. const fs = require('fs') module.exports = (client, Discord) =>{ const command_files = fs.reddirSync('./commands/').filter(file => file.endWith(' ...