【问题标题】:Angular authorization doesn't work due to CORS [duplicate]由于CORS,角度授权不起作用[重复]
【发布时间】:2020-02-05 13:41:40
【问题描述】:

我有登录和授权的角度项目,问题是授权不适用于错误消息Access to XMLHttpRequest at 'https://myserver/api/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

我已经阅读了有关此主题的几个问题,主要解决方案是直接在浏览器中禁用 CORS 或借助扩展程序。有没有可能以另一种方式解决这个问题,也许用一些角度的代码?

这是我的 login.ts 组件:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';

import { AuthenticationService } from '@services/auth.service';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {
  loginForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;
  error = '';

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService
  ) {
    // redirect to home if already logged in
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.registerForm = this.formBuilder.group({
      email: [''],
      password: [''],
      first_name: [''],
      last_name: [''],
      phone: ['']
    });

    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['/feed'] || '/';
  }

  // convenience getter for easy access to form fields
  get f() { return this.loginForm.controls; }

  onLogin() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }

    this.loading = true;
    this.authenticationService.login(this.f.username.value, this.f.password.value)
      .pipe(first())
      .subscribe(
        data => {
          this.router.navigate([this.returnUrl]);
        },
        error => {
          this.error = error;
          this.loading = false;
        });
  }
}

还有 auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { environment } from '../../environments/environment';
import { User } from '@models/user.model';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  private currentUserSubject: BehaviorSubject<User>;
  public currentUser: Observable<User>;

  constructor(private http: HttpClient) {
    this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.currentUser = this.currentUserSubject.asObservable();
  }

  public get currentUserValue(): User {
    return this.currentUserSubject.value;
  }

  login(username: string, password: string) {
    return this.http.post<any>(`${environment.apiUrl}/api/auth`, { username, password })
      .pipe(map(user => {
        // store user details and jwt token in local storage to keep user logged in between page refreshes
        localStorage.setItem('currentUser', JSON.stringify(user));
        this.currentUserSubject.next(user);
        return user;
      }));
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
  }
}

也许我可以通过在我的请求中添加标头来避免这种行为?感谢您的帮助。

【问题讨论】:

    标签: angular cors


    【解决方案1】:

    是的,禁用 CORS 可能很危险 - 在浏览编码提示时忘记启用它几次。我使用代理解决了这个问题。

    1. 在项目的根文件夹中创建代理配置文件,例如。 proxy.conf.json 内容:

    { "/api/v1": { "target": "https://www.example.com/", "secure": true, "changeOrigin": true } }

    如果端点是 HTTPS,则将安全设置为 true,如果是 HTTP,则设置为 false。上述设置假设您的 API 位于 example.com 的 /api/v1 中。相应调整。

    1. 将 package.json 中的启动命令修改为:

    "start": "ng serve --proxy-config proxy.conf.json"

    代理仅适用于本地主机。编译后的代码不会调用proxy.conf.json。

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2020-09-03
      • 2018-04-13
      • 2019-01-25
      • 2017-06-22
      相关资源
      最近更新 更多