0

I am new in Angular 7. I am working in a Angular 7 project. I have a login component like below

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TokenService } from '../../token.service'
import { Router, ActivatedRoute } from '@angular/router';
import { ServerService } from 'src/app/server.service';

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

    response: any;
    failmsg: boolean = false;
    constructor(private http: HttpClient,
        private server: ServerService,
        private Token: TokenService,
        private router: Router,
        private _router: ActivatedRoute

    ) { }

    public form = {
        grant_type: 'password',
        client_id: 2,
        client_secret: 'W5nQYuW1OFknDwiDnU96Y7dBMqTJ5jG6r6AXYk9q',
        username: null,
        password: null
    }

    headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.handleResponse2()
    });

    login() {
        this.http.post(this.server.base_url + "login", this.form).subscribe(  //execution is not entering inside this block
            (data) => {
                this.handleResponse(data);
                this.http.get(this.server.base_url + "employees/employee/user/profile", { headers: this.headers }).subscribe(
                    (profile) => {
                        this.employeeProfile = profile;
                        if (this.employeeProfile.user_id == 1) {
                            this.router.navigate([this._router.snapshot.paramMap.get("portal") + '/home/dashboard'])
                                .then(rel => location.reload());
                        } else {
                            localStorage.setItem('employeeId', this.employeeProfile.employeeId);
                            localStorage.setItem('id', this.employeeProfile.id);
                            this.router.navigate([this._router.snapshot.paramMap.get("portal") + '/home/employee-dashboard'])
                                .then(rel => location.reload());
                        }

                    }
                )
            },
            (error) => {    //execution is entering inside this block
                console.log('hello');
                if (error) {
                    this.failmsg = true;
                }
                console.log(error);
            }
        );
    }

    employeeProfile: any;

    handleResponse(data) {
        this.Token.set(data.access_token);
        this.headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.handleResponse2()
        });
    }

    onClose() {}

    handleResponse2() {
        return this.Token.get();
    }

    ngOnInit() {
        localStorage.setItem('portal', this._router.snapshot.paramMap.get("portal"));
        this.server.set_base_url(this._router.snapshot.paramMap.get("portal"));
        this.server.set_base_url2(this._router.snapshot.paramMap.get("portal"));
    }
}

I can't login. I am getting error like below

enter image description here

My network tab is like below

enter image description here

Could anyone help me to fix this issue ?

abu abu
  • 6,599
  • 19
  • 74
  • 131

3 Answers3

1

You are not able to hit the backend endpoints because of CORS- Cross origin resource sharing issue. You can check this link for more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

To fix this issue in angular you need to use --proxy-config option with your ng serve command. First, you need to create a JSON file proxy.conf.json and add below content:

{
  "/al-asr": {
    "target": "http://alasr.com",
    "secure": false
  }
}

I am assuming, Your backend is running in url http://alasr.com and url base is /al-asr.

Also in your httpClient pass the url like this

this.http.get('/al-asar/api/in/v1/employees/employee/user/profile')

Now run the server with below command to fix this issue:

ng serve --proxy-config proxy.conf.json

Ajit Soman
  • 3,926
  • 3
  • 22
  • 41
  • Thanks @Ajit Soman for your reply. I am using below code `{ "/al-asr": { "target": "http://localhost:4200", "secure": false } }`. I am getting below error `Error occured while trying to proxy to: localhost:4200/al-asr/login` – abu abu Jun 14 '19 at 04:53
  • Thanks @Ajit Soman. No, backend is running in `http://alasr.com/al-asar/api/in/v1/`. Thanks. – abu abu Jun 14 '19 at 05:25
1

Your target in proxy.conf should be http://alasr.com not localhost:4200.

What happen is --proxy-config option will treat http://alasr.com as though it is running on the same port as ur angular which is localhost:4200. So there will be no Cross Origin problem.

Btw, u can use npm 'start' script to give the proxy.conf file to the --proxy-config option

Gouk
  • 137
  • 1
  • 4
  • Thanks @Gouk. Here is my proxy.conf file. https://i.stack.imgur.com/Rf9yi.png. I am using `ng serve --proxy-config proxy.conf.json`. But I am getting same result as before. Thanks. – abu abu Jun 16 '19 at 15:41
  • 1
    in proxy you can insert `"changeOrigin": true` option as well. It will probably work then – adibro500 Jun 20 '19 at 09:23
0

Try this

{
    "/api": {
        "target": "https://9c8c4aa0.ngrok.io",
        "secure": true,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}
Maelig
  • 2,046
  • 4
  • 24
  • 49
Kishor Namdeo
  • 111
  • 1
  • 7