I was trying to get results from a local server. The class which I am using in the service is as follows:
@Injectable()
export class GridSearchService {
server = 'http://127.0.0.1:8100';
searchURL = this.server + '/yacy/grid/mcp/index/yacysearch.json?query=';
constructor(private http: Http,
private jsonp: Jsonp,
private store: Store<fromRoot.State>) {
}
getSearchResults(searchquery) {
return this.http
.get(this.searchURL+searchquery).map(res =>
res.json()
).catch(this.handleError);
}
but I was getting this error in console
Failed to load http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=india: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Then I followed this answer https://stackoverflow.com/a/37228330/7407321 and set headers accordingly. The new code looks like this:
@Injectable()
export class GridSearchService {
server = 'http://127.0.0.1:8100';
searchURL = this.server + '/yacy/grid/mcp/index/yacysearch.json?query=';
constructor(private http: Http,
private jsonp: Jsonp,
private store: Store<fromRoot.State>) {
}
getSearchResults(searchquery) {
let params = new URLSearchParams();
params.set('query',searchquery);
let headers = new Headers({ "Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Credentials":"true",
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"});
let options = new RequestOptions({ headers: headers, search: params });
return this.http
.get(this.searchURL,options).map(res =>
res.json()
).catch(this.handleError);
}
I get this error message now:
Failed to load http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=&query=india: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
Using a CORS plugin is working fine but can it be done without that.