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

时间:2017-11-17 07:20:44

标签: 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', []))
    );
}

错误:

  

对预检请求的响应未通过访问控制检查:请求的资源上不存在“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');

11 个答案:

答案 0 :(得分:34)

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

详细了解此here

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

proxy.conf.json

我将package.json文件放在同一目录下的"start": "ng serve --proxy-config proxy.conf.json" 文件旁边。

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

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

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

npm start

最后要运行我的应用,我必须使用ng serve --proxy-config proxy.conf.json或{{1}}

答案 1 :(得分:30)

CORS(跨域资源共享)是服务器说出的一种方式&#34;我会接受您的请求,即使您来自不同的来源。&#34;这需要服务器的合作 - 因此,如果您无法修改服务器(例如,如果您正在使用外部API),则此方法将无效。

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

答案 2 :(得分:3)

如果您像我一样,并且正在使用本地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
        }
      ));
  }

只需订阅即可。

答案 3 :(得分:2)

在NG5中为HttpClient创建标题:

let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'apikey': this.apikey,
        'appkey': this.appkey,
      }),
      params: new HttpParams().set('program_id', this.program_id)
    };

您可以使用localhost网址进行api通话,这对我有用 ..

  • 请永远不要忘记标题中的params columnd: 例如params:new HttpParams()。set('program_id',this.program_id)

答案 4 :(得分:2)

在Angular 6中使用httpClient进行的POST也正在执行OPTIONS请求:

标题:

Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:443
Referrer Policy:no-referrer-when-downgrade

我的Perl REST服务器实现带有返回码200的OPTIONS请求。

下一个POST请求标头:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:hp-probook
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36

注意Access-Control-Request-Headers:content-type。

因此,我的后端perl脚本使用以下标头:


 -"Access-Control-Allow-Origin" => '*',
 -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS',
 -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',

通过此设置,GET和POST为我工作了!

答案 5 :(得分:1)

请输入角球的请求选项

    import {RequestOptions, Request, Headers } from '@angular/http';

并在您的代码中添加请求选项,如下所示

    let requestOptions = new RequestOptions({ headers:null, withCredentials: 
    true });

在您的api请求中发送请求选项

下面的代码段 -

     let requestOptions = new RequestOptions({ headers:null, 
     withCredentials: true });
     return this.http.get(this.config.baseUrl + 
     this.config.getDropDownListForProject, requestOptions)
     .map(res => 
     {
      if(res != null)
      { 
        return res.json();
        //return true;
      }
    })
  .catch(this.handleError);
   }  

并在后端PHP代码中添加CORS,其中所有api请求将首先登陆。

尝试这个让我知道它是否正常工作我有同样的问题我从angular5添加了CORS但是没有工作然后我将CORS添加到后端并且它对我有用

答案 6 :(得分:1)

经过数小时的尝试,以下内容对我有用

rate_limit

但是下面的代码不起作用,我不清楚原因,希望有人可以改善这个答案。

image = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (800, 200)) #upscale
image = cv2.filter2D(image, -1, np.array([-1,4,-1])) #sharpen
print(pytesseract.image_to_string(image, config='--psm 7')) #use psm 7 since it is a single line

答案 7 :(得分:1)

您还可以尝试使用fetch功能和no-cors模式。有时我发现它比Angular的内置http模块更容易配置。您可以在“ Chrome开发者工具”的“网络”标签中右键单击请求,然后以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'
    }
  )
);

答案 8 :(得分:1)

将此评论添加到您的 API 文件中

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, PATCH");

我已经尝试实施这些解决方案,将 Laravel 的 CORS 标头响应添加到我的项目中,但我仍然没有成功:

https://github.com/barryvdh/laravel-cors

https://github.com/spatie/laravel-cors

我希望有人遇到过类似的问题并且可以提供帮助。

答案 9 :(得分:0)

使用jsonp ...

在调用API的应用程序中:

import { HttpClient } from "@angular/common/http";

this.httpClient.jsonp("http://127.0.0.1:3001/scicat/Publication", "callback")
...

在被叫方中:

import { Request, Response } from "express";

// is commonly cross a cross origin request
export let getPublication = (req: Request, res: Response) => {
  logger.debug("Get publications request.");
  const dao = MongoConnector.getInstance();
  dao
    .getPublication(req.query)
    .then(response => {
      Response.jsonp(response);
    })
    .catch(oaiError => {
      Response.status(500);
      Response.jsonp(oaiError);
    });
};

答案 10 :(得分:0)

为Chrome安装Moesif CORS扩展程序对我来说很有效。

相关问题