邮政请求被当地Angular应用程序中的CORS策略阻止,但在Postman和Thunder客户端效果很好

发布于 2025-02-12 16:45:34 字数 2773 浏览 0 评论 0原文

我正在开发一个Web应用程序,该应用程序以JSON的形式从远程服务器上的API中请求作业列表,因此我可以将它们插入垫子桌上。

该公司向我发送了一个我需要的API列表的链接,以及可以尝试使用请求的模板。为了澄清,看起来像 this

邮政请求就像模板上的魅力一样工作,邮递员和Thunder Client(在VSCODE上)。

  • 这些是响应标题:
 access-control-allow-credentials: * 
 access-control-allow-headers: content-type,server,strict-transport-security,x-powered-by,date 
 access-control-allow-methods: GET,HEAD,POST,PUT,DELETE,CONNECT,OPTIONS,TRACE,PATCH 
 access-control-allow-origin: * 
 access-control-expose-headers: * 
 content-type: application/json; charset=utf-8 
 date: Mon,04 Jul 2022 14:39:42 GMT 
 server: Microsoft-IIS/10.0 
 strict-transport-security: max-age=2592000 
 x-content-type-options: nosniff 
 x-powered-by: ASP.NET

但是,在执行我的Angular App的请求时,它会引起错误,这是勇敢的浏览器控制台上的错误:

Access to XMLHttpRequest at '(***API URL***)' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这是Mozilla Firefox控制台上的错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blmbwebapi.weker.fr/api/jobs/listJobs. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 405.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blmbwebapi.weker.fr/api/jobs/listJobs. (Reason: CORS request did not succeed). Status code: (null).

我的代码看起来像这样:

* list-jobs.service.ts: (SIPPET)

export class ListJobsService {

  public baseUrl = "/* API URL */";

  constructor(private httpClient: HttpClient) { }

  public getJobs(): Observable<any> { 

    let body = {"pageIndex": 0,
                "pageSize": 10,
                "filters": [ {"filterName": "csvFile", 
                              "filterValue": "flash-sales-export_20170217_080032.csv", 
                              "filterValues": [ "string" ] } ],
                "sortInfos": [ {"sortColumn": "string",
                                "sortOrdor": 0 } ] };


    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return this.httpClient.post(this.baseUrl,body, options);
   }

jobs.component.ts :( smippet)

ngOnInit(): void {

    this.listJobsService.getJobs().subscribe(data => {
      this.jobs = data;
      console.log(data);});
    
  }

如果需要进一步的信息,请告诉我!

太感谢了。

I'm developing a web app that requests a list of jobs from an api on a remote server, in the form of json, so I can insert them in a mat-table.

the company sent me a link to the list of API's that I need, along with a template that I can try requests with it. For clarification, it looks like this.

the POST request works like a charm on the template, with Postman and also Thunder Client (on VSCode).

  • these are the response headers:
 access-control-allow-credentials: * 
 access-control-allow-headers: content-type,server,strict-transport-security,x-powered-by,date 
 access-control-allow-methods: GET,HEAD,POST,PUT,DELETE,CONNECT,OPTIONS,TRACE,PATCH 
 access-control-allow-origin: * 
 access-control-expose-headers: * 
 content-type: application/json; charset=utf-8 
 date: Mon,04 Jul 2022 14:39:42 GMT 
 server: Microsoft-IIS/10.0 
 strict-transport-security: max-age=2592000 
 x-content-type-options: nosniff 
 x-powered-by: ASP.NET

However, it raises an error when performing the request from my Angular app, this is the error on Brave Browser Console:

Access to XMLHttpRequest at '(***API URL***)' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

This is the error on Mozilla Firefox Console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blmbwebapi.weker.fr/api/jobs/listJobs. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 405.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blmbwebapi.weker.fr/api/jobs/listJobs. (Reason: CORS request did not succeed). Status code: (null).

my code looks like this:

*list-jobs.service.ts: (Snippet)

export class ListJobsService {

  public baseUrl = "/* API URL */";

  constructor(private httpClient: HttpClient) { }

  public getJobs(): Observable<any> { 

    let body = {"pageIndex": 0,
                "pageSize": 10,
                "filters": [ {"filterName": "csvFile", 
                              "filterValue": "flash-sales-export_20170217_080032.csv", 
                              "filterValues": [ "string" ] } ],
                "sortInfos": [ {"sortColumn": "string",
                                "sortOrdor": 0 } ] };


    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return this.httpClient.post(this.baseUrl,body, options);
   }

jobs.component.ts:(Snippet)

ngOnInit(): void {

    this.listJobsService.getJobs().subscribe(data => {
      this.jobs = data;
      console.log(data);});
    
  }

If any further information is need, please tell me!

Thank you so much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠我空喜 2025-02-19 16:45:34

问题解决了,

我与Angular CLI代理一起工作,并在我的根文件夹中创建了 proxy.conf.json 文件。我需要通过假装将API具有相同的起源来欺骗我的浏览器。它不需要载体令牌或API键。

然后,我使用:

ng serve-proxy-config proxy.conf.json

我的proxy.conf.json文件包含以下内容:

{
    "/api": {
        "target": "(THE REAL API URL)",
        "secure": true,
        "changeOrigin": true,
        "pathRewrite": {
            "^/api": ""
        }
    }
}
  • /api对象指定属性,代理和
    嵌套对象指定配置。所以我改变了我的API
    服务方法中的URL http:// localhost:4200/api
  • pathrewrite属性允许我修改应用程序的方式
    与目标相互作用。

它变成了:

export class ListJobsService {

  public baseUrl = "http://localhost:4200/api";

  constructor(private httpClient: HttpClient) { }

  public getJobs(): Observable<any> { 

    let body = {"pageIndex": 0,
                "pageSize": 10,
                "filters": [ {"filterName": "csvFile", 
                              "filterValue": "flash-sales-export_20170217_080032.csv", 
                              "filterValues": [ "string" ] } ],
                "sortInfos": [ {"sortColumn": "string",
                                "sortOrdor": 0 } ] };


    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return this.httpClient.post(this.baseUrl,body, options);
   }

Problem Solved

I worked around it with Angular CLI Proxy, and created a proxy.conf.json file in my root folder. I needed to fool my browser by by pretending to have the API on the same origin. there is no Bearer token or API Key needed for it.

then I started my app with:

ng serve --proxy-config proxy.conf.json

my proxy.conf.json file contains this:

{
    "/api": {
        "target": "(THE REAL API URL)",
        "secure": true,
        "changeOrigin": true,
        "pathRewrite": {
            "^/api": ""
        }
    }
}
  • /api property of the object specifies the route for the proxy and
    the nested object specifies the configuration. So I changed my api
    url in the service method to http://localhost:4200/api.
  • pathRewrite property allowed me modify how the application
    interacts with the target.

It became:

export class ListJobsService {

  public baseUrl = "http://localhost:4200/api";

  constructor(private httpClient: HttpClient) { }

  public getJobs(): Observable<any> { 

    let body = {"pageIndex": 0,
                "pageSize": 10,
                "filters": [ {"filterName": "csvFile", 
                              "filterValue": "flash-sales-export_20170217_080032.csv", 
                              "filterValues": [ "string" ] } ],
                "sortInfos": [ {"sortColumn": "string",
                                "sortOrdor": 0 } ] };


    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return this.httpClient.post(this.baseUrl,body, options);
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文