我使用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; }); }
这是我在控制台中出现的错误:
我现在得到这个错误:未捕获的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; }); }
Access-Control-Allow-Origin标头是响应中应该存在的,而不是在请求中。
如果您的服务支持CORS,它必须在响应头中返回以允许该请求。所以这不是您的Angular应用程序的问题,但它是必须在服务器端级别处理的东西…
如果您需要更多详细信息,可以查看此链接:
>了解和使用CORS – http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
>调试CORS – http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/
编辑
似乎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; }); }
有关详细信息,请参阅此链接:
> https://angular.io/docs/ts/latest/api/http/JSONP_PROVIDERS-let.html