How to add CORS request in header in Angular 5

I added the CORS header, but I'm still getting the CORS problem in my request. What is the correct way to add and handle CORS and other requests in headers?

Here is the service file code:

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

Mistake:

The response to the preflight check request does not pass the access control check. There is no "Access-Control-Allow-Origin" header on the requested resource. Origin ' http: // localhost: 4200 ', therefore access is not allowed

failed: Http error response for (unknown url): 0 Unknown error

In my server code, I added CORS to 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');
+58
source share
10 answers

CORS ( Cross-Origin) - : " , ". - , (, API), .

, Access-Control-Allow-Origin: *, ( *).

+37

HTTP, httpClient. , CORS . , proxy.conf.json -.

.

proxy.conf.json:

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

proxy.conf.json package.json .

package.json:

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

HTTP- :

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

, , npm start ng serve --proxy-config proxy.conf.json

+39

, HttpClient NG5:

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

API URL , ..

  • , params : , params: new HttpParams(). Set ('program_id', this.program_id)
+2

POST httpClient Angular 6 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 OPTIONS 200.

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 !

+2

, requesttoptions

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

,

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

API

below-

     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);
   }  

CORS - PHP, API .

, , , CORS angular5, , CORS ,

+1

fetch no-cors. , Angular http. Chrome Dev , .

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'
    }
  )
);
+1

angular 2+ , API JSON. , - JSON.

print $response;

return $response;

Note : I ran into a problem in a corner app. The developer uses print to return the response.

0
source

The following worked for me after hours of trying

      $http.post("http://localhost:8080/yourresource", parameter, {headers: 
      {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).

However, the following code did not work, it is not clear to me why, I hope someone can improve this answer.

          $http({   method: 'POST', url: "http://localhost:8080/yourresource", 
                    parameter, 
                    headers: {'Content-Type': 'application/json', 
                              'Access-Control-Allow-Origin': '*',
                              'Access-Control-Allow-Methods': 'POST'} 
                })
0
source

Using jsonp ...

in the application calling the API:

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

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

In the called party:

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);
    });
};
0
source

All Articles