如何在Angular 5中的头文件中添加CORS请求

Ama*_*mar 63 angular angular5

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

这是服务文件代码:

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', []))
    );
}
Run Code Online (Sandbox Code Playgroud)

错误:

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

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

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

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');
Run Code Online (Sandbox Code Playgroud)

rga*_*tla 42

根据我的经验,插件使用HTTP但不使用最新的httpClient.此外,在服务器上配置CORS响应头并不是一个真正的选择.所以,我创建了一个proxy.conf.json文件来充当代理服务器.

在这里阅读更多相关信息.

proxy.conf.json 文件:

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

"start": "ng serve --proxy-config proxy.conf.json"
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 这在生产版本中不起作用,因此它不是一个合适的解决方案 (9认同)
  • 它仅用于开发目的.您无法使用该代理工具构建应用 (3认同)

Nav*_*dar 39

CORS(跨源资源共享)是服务器说"我会接受您的请求,即使您来自不同的来源"的一种方式.这需要服务器的合作 - 所以如果你不能修改服务器(例如,如果你使用外部API),这种方法将无法工作.

修改服务器以添加标头Access-Control-Allow-Origin:*以从任何地方启用跨源请求(或指定域而不是*).

  • 我认为浏览器(不是服务器)如​​果没有看到该标头,则拒绝该请求。如果我错了请纠正我 (4认同)

met*_*mit 8

您也可以尝试fetch功能和no-cors模式。有时我发现配置它比 Angular 的内置 http 模块更容易。您可以在 Chrome Dev tools network 选项卡中右键单击请求,然后将它们复制到 fetch 语法中,这很棒。

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);
Run Code Online (Sandbox Code Playgroud)


Avr*_*gil 6

如果您像我一样使用本地 SMS 网关服务器,并且向 192.168.0.xx 这样的 IP 发出 GET 请求,您肯定会得到 CORS 错误。

不幸的是,我找不到 Angular 解决方案,但在之前重播的帮助下,我得到了我的解决方案,我正在发布 Angular 7 8 9 的更新版本

import {from} from 'rxjs';

getData(): Observable<any> {
    return from(
      fetch(
        'http://xxxxx', // the url you are trying to access
        {
          headers: {
            'Content-Type': 'application/json',
          },
          method: 'GET', // GET, POST, PUT, DELETE
          mode: 'no-cors' // the most important option
        }
      ));
  }
Run Code Online (Sandbox Code Playgroud)

只需像往常一样订阅即可。