问题描述
我是Angular2的新手.而且我正在尝试将POST方法调用到.net核心API中.它与Postman正常工作.但是,当我从angular 2服务中调用它时,会出现错误.
I'm new to Angular2. And I'm trying to call POST method to my .net core API.It's working fine with Postman.But when I call it from my angular 2 service it gives an error.
这是我的api.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
@Injectable()
export class ApiService {
constructor(
private http: Http,
private jwtService: JwtService
) {}
private setHeaders(): Headers {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = `Token ${this.jwtService.getToken()}`;
}
return new Headers(headersConfig);
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
身体价值
.net核心API方法
.net core API mothod
推荐答案
这是CORS问题.发生这种情况是因为您试图从其他主机请求资源.您的API需要正确回答这些OPTIONS请求,否则浏览器将阻止该请求.
That's a CORS issue. It happens because you are trying to request a resource from a different host. Your API needs to answer those OPTIONS requests properly otherwise the browser is going to block the request.
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS
CORS保护未在邮递员中实现,因此您的请求在此可以正常工作.
CORS protection isn't implemented in postman so your request works fine there.
如果您的后端要在生产环境中的同一主机上运行,则还可以使用webpack/angular cli的代理支持: https://github.com/angular/angular -cli/blob/master/docs/documentation/stories/proxy.md
You can also use webpack / angular cli's proxy support if your backend is going to run on the same host in production:https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
这篇关于Angular 2对预检请求的响应未通过访问控制检查:没有"Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!