angular - CORS 策略已阻止访问位于 "http://...."源 'http://localhost:4200' 的 XMLHttpRequest

标签 angular angular-material

我正在尝试调用一个我遇到 CORS 错误的 api。

当我尝试使用 "https://...."时,我遇到了以下错误,服务失败。

状态码:422。

选项 https://xyz/login?username=xxx&password=xxx 422(无法处理的实体) 在 ' https://xyz/login?username=xxx&password=xxx 访问 XMLHttpRequest '来自原产地' http://localhost:4200 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。

当我尝试使用“http://....”时,我收到以下错误。

状态码:307 临时重定向

在' http://xyz/login?username=xxx&password=xxx 访问 XMLHttpRequest '来自原产地' http://localhost:4200 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

我尝试添加标题,但添加的标题不会显示在浏览器上。

请求 header 如下所示:

显示临时标题 访问控制请求 header :内容类型 访问控制请求方法:POST 来源:http://localhost:4200 推荐人:http://localhost:4200/login 用户代理:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36

请帮我解决问题,

我的 component.ts 看起来像这样

import { FormControl, FormGroup, FormGroupDirective, NgForm, Validators, FormBuilder } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { Router, ActivatedRoute } from '@angular/router';
import { first } from 'rxjs/operators';

import { AuthenticationService } from '../services';


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

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService) {}

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

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

   get f() { return this.loginForm.controls; }

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

}```

and my authentication.service.ts looks like this 

``import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Http, Headers, RequestOptions, Response, ResponseContentType } from '@angular/http';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {

    constructor(private http: HttpClient) { }

    login(username: string, password: string) {
      const httpOptions = {
       headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': 'true'
       })
     };
        return this.http.post(`https://xyz/login 
                         username=xxx&password=xxx, httpOptions)
            .pipe(map(user => {
                if (user) {
                    // some logic
                }
                return user;
            }));
    }
}```

i want to resolve the CORS issue and make successful api call either from client side or from server side. Being fairly new to angular, any details/step by step instructions are appreciated.

Also , i would want to know why added headers wont show on browser. Am i missing anything

最佳答案

从 localhost 开发时,CORS 问题很常见。你有一些选择来解决这个问题:

1) 如果您可以控制您的服务器,请将此 header 添加到响应中:

Access-Control-Allow-Origin: *

2) 如果您不拥有带有端点的服务器,请安装 this chrome extension .这将添加 header 并允许本地主机请求。

3) 如果您不使用 chrome 或者如果您想在代码中使用代理,请使用 this proxy .你的网址最终会是这样的:

https://crossorigin.me/http://xyz/login?username=xxx&password=xxx

关于angular - CORS 策略已阻止访问位于 "http://...."源 'http://localhost:4200' 的 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108555/

相关文章:

javascript - CSV 格式的 Angular 数据中的逗号相关问题

angular - HTTP 错误 500.19 - 托管 Angular 4 应用程序后出现内部服务器错误

html - HTML5 模式下的 NGINX、proxy_pass 和 SPA 路由

angular - 如何以 Angular 使用来自另一个语言环境的 Assets ?

Angular 组件动态编译 - ng-content 与选择不工作

angular - 允许在 cdkDropList 中水平定位

angular - 全局关闭 Material matInput 上的自动完成功能

javascript - react Angular Material 数据表

css - 无法在 md-tabs 中将 md-button 置于前台

angular - 将鼠标悬停在垫标签上时不会触发 mouseenter 和 mouseleave