aki*_*aki 3 angular-material angular
我正在尝试调用一个 api,在那里我遇到了 CORS 错误。
当我尝试使用 "https://...." 时,我遇到了以下服务失败的错误。
状态代码:422。
选项https://xyz/login?username=xxx&password=xxx 422 (Unprocessable Entity) 访问 XMLHttpRequest at ' https://xyz/login?username=xxx&password=xxx ' from origin ' http://localhost:4200 '被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
当我尝试使用“http://....”时,出现以下错误。
状态代码:307 临时重定向
CORS 策略阻止了在 ' http://xyz/login?username=xxx&password=xxx '处访问 XMLHttpRequest,来自源 ' http://localhost:4200 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:重定向不允许用于预检请求。
我尝试添加标题,但添加的标题不会显示在浏览器上。
请求标头如下所示:
显示临时标头 Access-Control-Request-Headers: content-type Access-Control-Request-Method: POST Origin: http://localhost:4200 Referer: http://localhost:4200/login User-Agent: 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
Run Code Online (Sandbox Code Playgroud)
从本地主机开发时,CORS 问题很常见。您有一些选择来解决这个问题:
1)如果您可以控制服务器,请将此标头添加到响应中:
Access-Control-Allow-Origin: *
Run Code Online (Sandbox Code Playgroud)
2) 如果您不拥有带有端点的服务器,请安装此 chrome 扩展。这将添加标头并允许本地主机请求。
3) 如果您不使用 chrome 或者您想在代码中使用代理,请使用此代理。你的网址最终会是这样的:
https://crossorigin.me/http://xyz/login?username=xxx&password=xxx
Run Code Online (Sandbox Code Playgroud)
我已经使用 fetch api 和 cors-anywhere 代理来解决这个问题。
\n\nonSubmit({ value, valid }: { value: IUserLogin, valid: boolean }) {\n let result;\n const params = {\n "username": value.username,\n "password": value.password\n }\n\n let url = `https://company.com/login?username=${params.username}&password=${params.password}`;\n const proxyurl = "https://cors-anywhere.herokuapp.com/";\n let req = new Request(proxyurl + url, {\n method: \'POST\',\n headers: {\n\n \'Authentication\': `Basic ${value.username}:${value.password}`,\n \'Content-Type\': \'application/json\',\n \'mode\': \'no-cors\'\n\n }\n });\n\n fetch(req)\n .then(response => response.text())\n .then((contents) => {\n result = JSON.parse(contents);\n console.log(JSON.parse(contents).data)\n if (result.data) {\n // do something\n } else {\n // do something\n }\n })\n .catch(() => console.log("Can\xe2\x80\x99t access " + url + " response. Blocked by browser?"))\n\n\n}\nRun Code Online (Sandbox Code Playgroud)\n