Reputation: 623
I am creating small application to get html content from website url using angular cli. i have added imported all required file but i am getting this error:
XMLHttpRequest cannot load https://www.test.org/publicclass/index.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
how we can solve this issue.
script:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as jQuery from 'jquery';
import { Http, Headers, RequestOptions } from '@angular/http';
@Component({
selector: 'app-bodycontent',
templateUrl: './bodycontent.component.html',
styleUrls: ['./bodycontent.component.css']
})
export class BodycontentComponent implements OnInit {
title = 'app';
results = '';
constructor(private http: HttpClient){
}
ngOnInit(): void {
let headers = new Headers({ 'Content-Type': 'text/html' });
let options = new RequestOptions({ headers: headers });
this.http.get('https://www.test.org/publictest/index.html').subscribe(html => {
alert(html);
});
}
}
Upvotes: 1
Views: 974
Reputation: 539
For web security purpose, all the browsers follow SOP (Same Origin Policy)
You can know more about SOP here
So if you are fetching web service response for your application not abiding these SOP rules, you see these errors in your console.
To Overcome that, you can use CORS plugin for chrome. That will solve you problem.
Upvotes: 1
Reputation: 2322
The server at https://www.test.org/publicclass/index.html needs to supply a header that tells browser that your site is allowed to request data from them. it should send a header something like the following with response-
Access-Control-Allow-Origin: http://localhost:8080
then you would be able to use resource from that url into your page.
alternately, if its only for your local environment there are browser extension available (for almost all major browsers) that help bypass this restriction. you can use them.
Upvotes: 2