I am trying to call an x-api-key in the header of an angular service but am missing something in the syntax. So far my code spits out an authorization error.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class PrecipForecastService {
constructor(private http:HttpClient) { }
getData () {
const url = 'url_here';
const key = 'key_here';
const header = new HttpHeaders({'x-api-key': key});
return this.http.get(url, {headers: header});
}
}
The browser's network tab shows:
Access to XMLHttpRequest at 'url_here' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Yes the key is correct, it worked with the JS fetch module.
Thanks for the help!
Today, I ran into the EXACT same issue.
After checking the network tab in the dev console of Chrome (hit F12),
I found an interesting preflight response:
Here, the access-control-allow-headers deliver the answer to the problem. They simply don't allow X-API-Key, but instead I was able to use access-token and then it worked... at least I didn't get a CORS error anymore.
In my case, the api docs were just 'buggy'.
hth
Related
On redash I have a query. It's GET request. On POSTMAN it works well.
Query example:
https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key>
But on axios it throws:
Network error
And on console written:
Access to XMLHttpRequest at https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key> from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My axios default configs:
import axios from 'axios/index';
import { appVersion } from '../../constants/defaultValues';
const { CancelToken } = axios;
export const source = CancelToken.source();
const api = axios.create({
timeout: 5 * 60 * 1000,
headers: {
version: appVersion,
},
cancelToken: source.token,
});
export default api;
It's not from your code. your code is right
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API.
You can read more about Cross-Origin Resource Sharing
I want to use /data/todo.js file in my reactjs component. I have used axios http request to get this data in my react component i.e.,
import React, { Component } from 'react';
import axios from 'axios';
class TodoList extends Component {
componentWillMount() {
var config = {
headers: {
"Access-Control-Allow-Origin": "http://localhost:8080/",
"Access-Control-Allow-Credentials": true
}
};
axios.get('http://abc.mydomain.org/data/todo.js', config)
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<div className="todo-list"></div>
);
}
}
export default TodoList;
It gives an error
XMLHttpRequest cannot load http://abc.mydomain.org/data/todo.js. 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:8080' is therefore not allowed access.
You are trying to access a cross-origin HTTP request from you application, which is by default blocked by the browser.
To access the resource, Cross-Origin Resource Sharing (CORS) should be enabled at the application you are trying to access (In your case http://abc.mydomain.org)
For security reasons, browsers restrict cross-origin HTTP requests
initiated from within scripts. For example, XMLHttpRequest and the
Fetch API follow the same-origin policy. This means that a web
application using those APIs can only request HTTP resources from the
same domain the application was loaded from unless CORS headers are
used.
You can check more on this here
I'm trying to set the header key and value using HttpInterceptor however, I'm getting this error:
Failed to load
https://example.com/api/agency:
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. The response had HTTP status code 403.
import {Injectable} from '#angular/core';
import {Observable} from 'rxjs';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '#angular/common/http';
#Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('x-api-key', 'MY_TOKEN_VALUE')});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
The header key is x-api-key.
The API was hosted on Amazon AWS so I had to setup proxy which fixed the issue.
I have one web service in jersey that deploy on appache server, and I'm trying to connect that server but I get the following error :
Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
my service.ts file code is below
getlogin(): Observable<ILogin[]> {
return this._http
.get(this._loginurl, this.headers)
.map((response: Response) => <ILogin[]> response.json())
.catch(this.handleError);
}
this is my server url
_loginurl='http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/'+this.encodedString;
please help me to solve this..thank you!!
Try This
getlogin(): Promise<ILogin[]> {
return this.http.get(this._loginurl)
.toPromise().then(response => <ILogin[]>response.json().data)
.catch(this.handleError);
}
The error clearly says:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is not an error with angular2 itself. But it's more to do with your CORS configuration on server side.
You have to set Access-Control-Allow-Origin header in your response from your service. You can set something like below which says you basically allow any resource:
Access-Control-Allow-Origin: *
try this:
import {Headers} from "#angular/http";
let headers=new Headers({
});
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin','*');
getlogin(): Promise<ILogin[]> {
return this.http.get(this._loginurl,{headers:headers}))
.toPromise().then(response => <ILogin[]>response.json().data)
.catch(this.handleError);
}
I am trying to connect to an API using Angular 2. I am unable to connect to it as it is giving me a OPTIONS error as well as:
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:3000' is therefore not allowed access. The response had HTTP status code 500.
I have the Google Chrome plugin as well as the headers. Here is the code
map.service.ts
import { Injectable } from '#angular/core';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class MapService {
private headers = new Headers();
constructor(private http: Http) { }
getMarkers() {
this.headers.append("Access-Control-Allow-Origin", '*');
this.headers.append("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
this.headers.append("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token');
this.headers.append("Authorization", 'Bearer ' + 'mysecretcode');
return this.http.get('https://api.yelp.com/v3/businesses/search?location=suo&limit=50', { headers: this.headers})
.map(response => response.json());
}
}
map.component.ts
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
import { Marker } from '../../models/map/marker';
import { MapService } from '../../services/map/map.service';
import {Observable} from 'rxjs/Rx';
import {Http, Response, Headers } from '#angular/http';
#Component({
moduleId: module.id,
selector: 'map-view',
templateUrl: 'map.component.html',
styleUrls: ['map.component.css'],
})
export class MapComponent {
marker: Object;
constructor(mapService: MapService) {
mapService.getMarkers()
.subscribe(
marker => this.marker = marker,
error => console.error('Error: ' + error),
() => console.log('Completed!')
);
}
I understand that this is most likely a problem with CORS. Is this something i can do to fix or is this on yelps end?
EDIT:
Here is one of the errors:
Error: Response with status: 0 for URL: null(anonymous function) # map.component.ts:24SafeSubscriber.__tryOrUnsub # Subscriber.ts:238SafeSubscriber.error # Subscriber.ts:202Subscriber._error # Subscriber.ts:139Subscriber.error # Subscriber.ts:109Subscriber._error # Subscriber.ts:139Subscriber.error # Subscriber.ts:109onError # http.umd.js:1186ZoneDelegate.invokeTask # zone.js:262onInvokeTask # core.umd.js:7768ZoneDelegate.invokeTask # zone.js:261Zone.runTask # zone.js:151ZoneTask.invoke # zone.js:332
The reason for pre-flight failing is a standard problem with CORS:
How does Access-Control-Allow-Origin header work?
It is fixed by having server to set correct Access-Control-Allow-Origin.
However, the root cause of your problem could be in misconfiguration of your server or your client, since 500 is the server internal error. So it might not be accessing intended server code, but some generic handler in apache or whatever is hosting the service. Most of the generic error handlers dont provide CORS support as default.
Note, if you are using REST API, 500 is not a code you should see in a successful API use scenario. It means that the server is not capable of handling the request properly.
Maybe this link would have relevant information:
EXCEPTION: Response with status: 0 for URL: null in angular2