Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue:

Access the complete project here:

Link to a Plunker example of a log-in screen:

http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview

(The username and password for this example are both set as "test")

Snippet with the error in the code:

  return this.http.post('/auth/login', JSON.stringify({})

Full script of dashboard.component.ts

import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroService} from './hero.service';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HeroesComponent} from './heroes.component';
import {HeroDetailComponent} from './hero-detail.component';
import {SpreadSheetComponent} from './spreadsheeteditall.component';
import {SwitchUsersComponent} from './SwitchUsers.component';
import {BiddingPageComponent} from './BiddingPage.component';
import { Injectable } from 'angular2/core';
import { Jsonp, URLSearchParams } from 'angular2/http';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {JSONP_PROVIDERS} from 'angular2/http';
@Component({
  selector: 'my-dashboard',
  templateUrl: 'app/dashboard.component.html',
  styleUrls: ['app/dashboard.component.css'],
  directives: [ROUTER_DIRECTIVES],
  providers : [HTTP_PROVIDERS, Http],
})
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private _http: Http, private _heroService: HeroService, private _router: Router) {
        this.token = localStorage.getItem('token');
   }

  ngOnInit() {
    this._heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1,5));
  }

  gotoDetail(hero: Hero) {
    let link = ['HeroDetail', { id: hero.id }];
    this._router.navigate(link);
  }
  @Injectable()

  token: string;


  login(username: String, password: String) {


   return this.http.post('/auth/login', JSON.stringify({});
   // username: username,
   //  password: password
   //  }), {
   //   headers: new Headers({
    //   'Content-Type': 'application/json'
  //  })
  //  })

    //  .map((res : any) => {
    //    let data = res.json();
    //    this.token = data.token;
    //    localStorage.setItem('token', this.token);
    //  });

    //  For demonstration purposes only, we will simulate this

    if (username === 'test' && password === 'test') {
      this.token = 'token';
      localStorage.setItem('token', this.token);
      //return Rx.Observable.of('token');
    }

    //return Rx.Observable.throw('authentication failure');
  ,

  logout() {

   }}
/*
    return this._http.get(this.config.serverUrl + '/auth/logout', {
      headers: new Headers({
        'x-security-token': this.token
      })
    })
    .map((res : any) => {
      this.token = undefined;
      localStorage.removeItem('token');
    });


 //   this.token = undefined;
 //   localStorage.removeItem('token');

   // return Rx.Observable.of(true);
  }
}

Answer №1

Give this a shot (replace http with _http):

return this._http.post('/auth/login', JSON.stringify({})

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

Deciphering the AngularJS Component Hierarchy and Managing Identifiers for Freshly Generated Objects (using HTTP)

In my project using Angular 1, I have developed a todo list application which consists of two components. The first is a smart (container) component responsible for server-side interactions, while the second is a dumb/pure/stateless presentation component ...

Tips on ensuring a <video> element occupies the full height and width of the screen

I am currently working on an Angular 6 project where I am live streaming a user's webcam to an HTML element. My goal is to simulate the experience of capturing a video or photo on a mobile device. However, the size of the video is currently small. I ...

Googlebot is unable to view structured data tags generated in an Angular single-page application (SPA)

During live testing a URL on Google Search Console, I discovered that while Googlebot can render the page, the structured data is missing. The structured data is generated in JavaScript using the following function: insertStructuredData(genDataFn: Function ...

Tips for wrapping text labels in mat-slide-toggles (Angular Material)

Is there a way to get the title in mat-slide-toggle to wrap if it's too long while keeping its default position to the right of the toggle? <mat-slide-toggle class="slider">A really long title wrapped</mat-slide-toggle> I attemp ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Encountering an issue with undefined error when performing two-way form binding with an object that implements an interface

I have defined an User interface: export interface User{ name:string; email:string: address:string; } After importing this interface on my Ionic page, I declared the following code in the class, just before the constructor: user:User; Later, in the ngO ...

Using Node.js to generate several MongoDB documents by iterating through JSON data submitted via POST requests

When a webpage sends JSON data via POST to my Node.js App (MEAN-environment using Mongoose), the format of the JSON file is as follows: Firstname: 'XY', Surname: 'asd', Articles: [ { title: '1', description: ...

Error 500 in WordPress Child Theme due to AJAX Internal Issue

I have encountered an issue with my Ajax code in the Js/Jq block (/buscador/menuLateral/menu-libros.php): $.ajax({ url: '<?= get_stylesheet_directory_uri(); ?>' + '/buscador/buscador-functions.php', type: 'POST' ...

Exploring the process of obtaining a collection of JSON sub-items and using Angular's method for finding a match within an array

Question 1 In my program, I am receiving a JSON object called scope.tagSet, which has the structure shown below. { Tags : [ {"TagID" : "ID1" , "TagName" : "Name1"}, {"TagID" : "ID2" , "TagName" : "Name2"}, {"TagID" : "ID3 ...

basic computation of whole and decimal values using jquery

I'm having trouble multiplying 2 values in my code where the quantity is an integer and credit price is a decimal number. However, when I run the script, nothing seems to happen. Can someone please help me identify and resolve this issue? Any insight ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

Is there a way for me to view the properties within the subcomponents?

Working on a project to create a bulletin board using React, following the official documentation. Decided to consolidate all actions related to the bulletin board into one alert component called AlertC. In the Form onSubmit statement, if the title is tr ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Understanding the flattening process of arrays using JavaScript - Detailed explanation required

Currently, I am immersed in the captivating world of Eloquent JavaScript. However, I have hit a roadblock with one of the exercises that involves flattening a multi-dimensional array. Despite my best efforts, I have been unable to crack the code. After f ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...