从本地角度设置访问github上可用的资源时出错

时间:2019-05-20 16:47:14

标签: angular cors

我正在尝试使用herehttp.get()获取js文件的内容,但是我却收到了Follow CORS错误。

Access to XMLHttpRequest at 'https://gist.github.com/nawnit1996/cbb37d9159d9f699a299a2d733f48abc.js' from origin 'http://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.

即使我在请求中设置标头,我也会收到此错误。我是否需要在标头中添加其他内容?

关于CORS的工作原理,有很多答案,但是都没有说从本地的angular站点调用某些网站上的http url时应该在标头'Access-Control-Allow-Origin'中加上什么值。

这是我的代码:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

@Component({
  selector: 'app-mycomp',
  templateUrl: './mycomp.component.html',
  styleUrls: ['./mycomp.component.css']
})
export class MycompComponent implements OnInit {

  constructor(@Inject(DOCUMENT) private document: any,private http: HttpClient) { 
    httpOptions.headers.append('Access-Control-Allow-Origin', '*');

  }

  ngOnInit() {
this.http.get('https://gist.github.com/nawnit1996/cbb37d9159d9f699a299a2d733f48abc.js', httpOptions).subscribe(data => {
   // console.log(data.text());
})  
}

0 个答案:

没有答案