【问题标题】:Angular 2 http request with Access-Control-Allow-Origin set to *Access-Control-Allow-Origin 设置为 * 的 Angular 2 http 请求
【发布时间】:2016-05-11 09:25:43
【问题描述】:

我正在使用 angular2 和 typescript。

我正在尝试发布到我的邮件黑猩猩订阅列表。

到目前为止我的代码:

 constructor(router: Router, http: Http){   
      this.router = router;

      this.http = http; 
      this.headers = new Headers();
      this.headers.append('Content-Type', 'application/json');
      this.headers.append('Access-Control-Allow-Origin', '*');
  }

  subscribe = () => {
        var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
        this.isSuccess = false;

        this.http.request(url, this.headers).subscribe(response => {
           console.log(response);
           this.isSuccess = true; 
        });   
  }

这是我在控制台中遇到的错误:

我现在收到此错误:Uncaught SyntaxError: Unexpected token

当前代码如下:

export class Footer{
  email: string = "";
  router : Router;
  http : Http;
  jsonp: Jsonp;
  isSuccess: boolean = false;

  constructor(router: Router, jsonp: Jsonp, http: Http){   
      this.router = router;
      this.http = http; 
      this.jsonp = jsonp;
  }

  subscribe = () => {
        var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
        this.isSuccess = false;

        this.jsonp.request(url).subscribe(response => {
           console.log(response);
           this.isSuccess = true; 
        });   
  }

【问题讨论】:

标签: angular angular-http


【解决方案1】:

Access-Control-Allow-Origin 标头应该出现在响应中,而不是请求中。

如果您的服务支持 CORS,它必须在响应标头中返回它以允许请求。所以这不是您的 Angular 应用程序的问题,而是必须在服务器端级别处理的问题...

如果您需要更多详细信息,可以查看此链接:

编辑

thepoolcover.us10.list-manage.com 似乎不支持 CORS 但支持 JSONP。您可以尝试按如下所述重构您的代码:

constructor(private router: Router, private jsonp: Jsonp){   
}

subscribe = () => {
  var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
  this.isSuccess = false;

  this.jsonp.request(url, this.headers).subscribe(response => {
    console.log(response);
    this.isSuccess = true; 
  });   
}

在调用bootstrap 函数时不要忘记指定JSONP_PROVIDERS

查看此链接了解更多详情:

【讨论】:

  • 上面的电话是寄给黑猩猩的。你知道它为什么抱怨吗?我认为邮件黑猩猩会是跨源的
  • 那个错误是因为尝试 jsonp,我在上面添加了我的新代码
  • 关于屏幕截图上面的错误有什么想法吗?
  • 也许您可以尝试使用https://thepoolcover.us10.list-manage.com/subscribe/post-json 而不是https://thepoolcover.us10.list-manage.com/subscribe/post...
  • 我浏览了一些 mailchimp 文档,我认为您应该改用 MailChimp API。请参阅此链接:developer.mailchimp.com/documentation/mailchimp/guides/…
【解决方案2】:

问题出在服务器端。您必须告诉您的服务接受 GET 请求。例如,在带有 Spring 的 JEE 中,您只需添加:

@CrossOrigin
@RequestMapping(value = "/something", method = RequestMethod.GET)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2018-04-16
    • 2017-06-08
    • 2015-12-24
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多