angularjs – 具有Access-Control-Allow-Origin的Angular 2 http请求设置为*

前端之家收集整理的这篇文章主要介绍了angularjs – 具有Access-Control-Allow-Origin的Angular 2 http请求设置为*前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用angular2和typescript。

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

我的代码到目前为止

  1. constructor(router: Router,http: Http){
  2. this.router = router;
  3.  
  4. this.http = http;
  5. this.headers = new Headers();
  6. this.headers.append('Content-Type','application/json');
  7. this.headers.append('Access-Control-Allow-Origin','*');
  8. }
  9.  
  10. subscribe = () => {
  11. var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
  12. this.isSuccess = false;
  13.  
  14. this.http.request(url,this.headers).subscribe(response => {
  15. console.log(response);
  16. this.isSuccess = true;
  17. });
  18. }

这是我在控制台中出现的错误

我现在得到这个错误:未捕获的SyntaxError:意外的标记< 当前代码如下:

  1. export class Footer{
  2. email: string = "";
  3. router : Router;
  4. http : Http;
  5. jsonp: Jsonp;
  6. isSuccess: boolean = false;
  7.  
  8. constructor(router: Router,jsonp: Jsonp,http: Http){
  9. this.router = router;
  10. this.http = http;
  11. this.jsonp = jsonp;
  12. }
  13.  
  14. subscribe = () => {
  15. var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
  16. this.isSuccess = false;
  17.  
  18. this.jsonp.request(url).subscribe(response => {
  19. console.log(response);
  20. this.isSuccess = true;
  21. });
  22. }
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。您可以尝试重构您的代码,如下所述:

  1. constructor(private router: Router,private jsonp: Jsonp){
  2. }
  3.  
  4. subscribe = () => {
  5. var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
  6. this.isSuccess = false;
  7.  
  8. this.jsonp.request(url,this.headers).subscribe(response => {
  9. console.log(response);
  10. this.isSuccess = true;
  11. });
  12. }

调用引导函数时不要忘记指定JSONP_PROVIDERS。

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

> https://angular.io/docs/ts/latest/api/http/JSONP_PROVIDERS-let.html

猜你在找的Angularjs相关文章