简体   繁体   English

角度登录问题

[英]Angular Login issue

I am new in Angular 7. I am working in a Angular 7 project. 我是Angular 7的新手。我在Angular 7项目中工作。 I have a login component like below 我有一个如下的login组件

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 我收到如下错误

在此输入图像描述

My network tab is like below 我的网络标签如下所示

在此输入图像描述

Could anyone help me to fix this issue ? 任何人都可以帮我解决这个问题吗?

You are not able to hit the backend endpoints because of CORS- Cross origin resource sharing issue. 由于CORS-跨源资源共享问题,您无法命中后端端点。 You can check this link for more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS 您可以查看此链接以获取更多信息: 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. 要以角度修复此问题,您需要在ng serve命令中使用--proxy-config选项。 First, you need to create a JSON file proxy.conf.json and add below content: 首先,您需要创建一个JSON文件proxy.conf.json并添加以下内容:

{
  "/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 . 我假设,你的后端运行在URL http://alasr.com和url base是/al-asr

Also in your httpClient pass the url like this 也在你的httpClient中传递这样的url

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

Your target in proxy.conf should be http://alasr.com not localhost:4200. 您在proxy.conf中的目标应该是http://alasr.com而不是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. 会发生什么--proxy-config选项会将http://alasr.com视为与ur angular相同的端口运行,即localhost:4200。 So there will be no Cross Origin problem. 所以不存在Cross Origin问题。

Btw, u can use npm 'start' script to give the proxy.conf file to the --proxy-config option 顺便说一句,您可以使用npm'start'脚本将proxy.conf文件提供给--proxy-config选项

Try this 尝试这个

{
    "/api": {
        "target": "https://9c8c4aa0.ngrok.io",
        "secure": true,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM