如何使用Angular 2请求数据。

3
当我们向外部api发送包含JSON内容的数据时,会出现一个Access-Control-Allow-Origin错误。解决这个问题的方法是使用x-www-form-urlencoded内容。 有没有办法改用JSON呢?
JSON内容:
    this.http.post('/api/login', {
      email: email,
      password: pass
    }).map(res => res.json())
      .subscribe(response => {
        console.log(response);
      } , error => console.error(error));
  }

x-www-form-urlencod:

  this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.options = new RequestOptions({ headers: this.headers, method: 'post'});
    return this.http.post('/api/login', "email=info@mail.com&password=123", this.options )
        .map(res => res.json())
        .map(user => {
            if (user) {
                console.log(user);
            }
            return !!user ;
        });
}

其他解决方案:

1.在Chrome中安装Access-Control-Allow-Origin扩展程序
2.查找另一种方法启动本地主机的Web API
3.在IIS7上启用CORS

但问题仍未解决!


2
这是一个CORS问题,你需要在你的API中启用它。 - Rahul Singh
@RahulSingh Web.config启用了CORS,但问题仍未解决。 - Allahyar
在 Postman 中检查一下。默认情况下,/token 是 MVC 中获取令牌的 URL。 - Habeeb
1个回答

1
WebConfig :
 <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol>​

WebApiConfig:
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET,POST,PUT,DELETE");
config.EnableCors(cors);

XMLHttpRequest无法加载/api/login。预检请求的响应未通过访问控制检查:'Access-Control-Allow-Origin'标头包含多个值'',但只允许一个。因此,来自'http://localhost:4200'的源不被允许访问。 - Allahyar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接