【发布时间】:2017-11-14 13:47:19
【问题描述】:
我正在尝试在 Angular 2 客户端(asp.net core 2.0 api 服务器)上执行 http POST 请求。
起初有一个415 error (Unsupported Media)。
当我添加标题时,出现response to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resource 错误。
同一服务中的 Http GET 运行良好(没有标头)。
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
export class MyService {
constructor(private http: Http) {}
// This is working
getStudents(): Observable <string[]>{
return this.http.get('https://localhost:44753/api/students', {withCredentials:true})
.map((res:Response)=> res.Json());
}
// Return 415
getStudent(name): Observable <string[]>{
let data = {
"name": name
}
return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data), {withCredentials:true})
.map((res:Response)=> res.Json());
}
// Return 401
getStudent2(name): Observable <string[]>{
let data = {
"name": name
}
let headers = new Header();
headers.append('Content-Type', 'application/json);
headers.append('Access-Control-Allow-Origin', '*');
let options = new RequestOptions({ headers:headers , withCredentials:true });
return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data), options)
.map((res:Response)=> res.Json());
}
}
有人可以帮我解决这个问题吗?
【问题讨论】:
-
您使用的是什么服务器?您使用的是 Angular 开发服务器还是某种生产服务器?如果您使用的是 Angular 2,是否可以升级到较新的版本 (5) 并查看是否可行?
标签: angular http post asp.net-core-2.0