【问题标题】:http get request to https://stackoverflow.com/jobs/feed fails with CORS对 https://stackoverflow.com/jobs/feed 的 http 获取请求因 CORS 失败
【发布时间】:2021-05-22 05:32:18
【问题描述】:

我想阅读 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)

【问题讨论】:

    标签: api http proxy get cors


    【解决方案1】:

    您确定在 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
    });
    

    【讨论】:

    • 我猜服务器端不允许使用 CORS,这就是我尝试使用代理的原因。使用代理应该可以,但不知道如何成功实现
    【解决方案2】:
    {
      "/proxy/*": {
      "target": "https://stackoverflow.com",
      "secure": false,
      "changeOrigin": true,
      "logLevel": "debug",
      "pathRewrite": {"^/proxy" : ""}
      }
    }
    

    这个代理配置解决了我的问题:)

    StackOverflow 参考:Angular-CLI proxy to backend doesn't work

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-14
      • 2015-04-03
      • 2013-02-02
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多