如何解决对 https://stackoverflow.com/jobs/feed 的 http get 请求因 CORS 失败
我想阅读 StackOverflow 作业 RSS 提要,我也尝试添加“Access-Control-Allow-Headers”和代理实现,但它出错了。请帮我实现这个[已解决,请参阅下面的答案]
API 网址:https://stackoverflow.com/jobs/feed
private proxyPrefix = '/api';
private hostName = 'stackoverflow.com';
private location='sydney'
private query = `location=${this.location}`;
private path = 'jobs/Feed';
private stackOverFlowJobsRSSFeedUrl = `${this.hostName}/${this.path}?${this.query}`;
constructor(private http: HttpClient) { }
private getData$(url: string): Observable<any> {
const requestOptions = { headers: new HttpHeaders({ 'Access-Control-Allow-Headers': '*' }) };
return this.http.get<any>(url,requestOptions);
}
private get stackOverflowJobs$(): Observable<any> {
const proxyURL = `${this.proxyPrefix}/${this.path}?${this.query}`;
return fromFetch(proxyURL,{
selector: response => response.json()
});
}
ngOnInit(): void {
// http get
this.getData$(this.stackOverFlowJobsRSSFeedUrl)
.subscribe((x) => {
console.log(x);
});
// rxJs fetch using proxy
this.stackOverflowJobs$.subscribe({
next: result => console.log('jobs:',result),complete: () => console.log('done')
});
}
proxy.config
{
"/api/jobs": {
"target": {
"host": "https://stackoverflow.com","protocol": "https:","port": 443
},"secure": false,"changeOrigin": true,"logLevel": "info"
}
}
[HPM] Error occurred while trying to proxy request /api/jobs/Feed?location=sydney from localhost:4200 to https://stackoverflow.com (ENOTFOUND) (https://nodejs.org/api/errors.html#errors_common_system_errors)
解决方法
您确定 SO 服务器端允许使用 CORS 吗?尝试从 SO 和开发工具中的另一个域控制台发送此信息,您将仅收到来自 SO 的响应。 一种选择是设置一些服务器并将其用作中间件,那么CORS问题将不相关
fetch('https://stackoverflow.com/jobs/feed')
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data); // this will be a string
});
,
{
"/proxy/*": {
"target": "https://stackoverflow.com","secure": false,"changeOrigin": true,"logLevel": "debug","pathRewrite": {"^/proxy" : ""}
}
}
这个代理配置解决了我的问题:)
StackOverflow 参考:Angular-CLI proxy to backend doesn't work
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。