将Access-Control-Allow-Origin设置为*的Angular 2 http请求

时间:2016-02-02 14:12:25

标签: angular angular-http

我使用angular2和打字稿。

我试图发布到我的邮件黑猩猩订阅列表。

到目前为止我的代码:

 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; 
        });   
  }

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

enter image description here

我现在收到此错误:未捕获的SyntaxError:意外的标记<

以下当前代码:

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; 
        });   
  }

2 个答案:

答案 0 :(得分:20)

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; 
  });   
}

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

有关详细信息,请参阅此链接:

答案 1 :(得分:1)

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

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