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

查看:70
本文介绍了如何在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"标头.因此,不允许访问' http://localhost:4200 '

失败:(未知网址)的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.

此处.

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天全站免登陆