如何在 Angular 5 的标头中添加 CORS 请求 [英] How to add CORS request in header in Angular 5

查看:24
本文介绍了如何在 Angular 5 的标头中添加 CORS 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在标头中添加了 CORS,但我的请求中仍然出现 CORS 问题.在标头中添加和处理 CORS 和其他请求的正确方法是什么?

I have added the CORS in header but I am still getting the CORS issue in my request. What is the correct way to add and handle CORS and other requests in the headers?

这里是服务文件代码:

import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
const httpOptions = {
  headers: new HttpHeaders({ 
    'Access-Control-Allow-Origin':'*',
    'Authorization':'authkey',
    'userid':'1'
  })
};

public baseurl = 'http://localhost/XXXXXX';

userAPI(data): Observable<any> {
  return this.http.post(this.baseurl, data, httpOptions)
    .pipe(
      tap((result) => console.log('result-->',result)),
      catchError(this.handleError('error', []))
    );
}

错误:

对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://localhost:4200' 因此不允许访问

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

失败:(未知 url)的 Http 失败响应:0 未知错误

failed: Http failure response for (unknown url): 0 Unknown Error

在我的服务器端代码中,我在索引文件中添加了 CORS.

In my server-side code, I've added CORS in the index file.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

推荐答案

根据我的经验,这些插件适用于 HTTP,但不适用于最新的 httpClient.此外,在服务器上配置 CORS 响应标头并不是一个真正的选择.因此,我创建了一个 proxy.conf.json 文件来充当代理服务器.这仅用于开发目的.

In my experience the plugins worked with HTTP but not with the latest httpClient. Also, configuring the CORS response headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server. This is for development purposes only.

此处阅读更多相关信息.

proxy.conf.json 文件:

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}

我将 proxy.conf.json 文件放在同一目录中 package.json 文件的旁边.

I placed the proxy.conf.json file right next the the package.json file in the same directory.

然后我修改了package.json文件中的启动命令:

Then I modified the start command in the package.json file:

"start": "ng serve --proxy-config proxy.conf.json"

来自我的应用组件的 HTTP 调用:

The HTTP call from my app component:

return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
  console.log(returnedStuff);
});

最后要运行我的应用程序,我必须使用 npm startng serve --proxy-config proxy.conf.json

Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json

这篇关于如何在 Angular 5 的标头中添加 CORS 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆