首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Access-Control-Allow-Origin设置为*的Angular 2 http请求

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

Stack Overflow用户
提问于 2016-02-02 22:12:25
回答 2查看 55K关注 0票数 16

我使用的是angular2和typescript。

我正试着发邮件到我的邮件黑猩猩订阅列表。

到目前为止,我的代码:

代码语言:javascript
复制
 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:意外的令牌<

当前代码如下:

代码语言:javascript
复制
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; 
        });   
  }
EN

回答 2

Stack Overflow用户

发布于 2016-02-02 22:14:02

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

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

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

了解和使用CORS - http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

编辑

似乎thepoolcover.us10.list-manage.com并不支持CORS,而是支持JSONP。你可以尝试重构你的代码,如下所述:

代码语言:javascript
复制
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

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

票数 20
EN

Stack Overflow用户

发布于 2017-07-03 21:45:14

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

代码语言:javascript
复制
@CrossOrigin
@RequestMapping(value = "/something", method = RequestMethod.GET)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35155752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档