2017-07-10 18 views
3

当我们将包括JSON内容的数据发送到外部API时,会发生Access-Control-Allow-Origin错误。这个问题的解决方案是使用x-www-form-urlencoded content。 反正有没有使用JSON呢?如何使用角度2请求数据

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 protected].com&password=123", this.options) 
     .map(res => res.json()) 
     .map(user => { 
      if (user) { 
       console.log(user); 
      } 
      return !!user ; 
     }); 
} 

其他解决方案:

1.安装访问控制允许来源扩展的Chrome
2.lunch网页API在localhost bu寻找另一种方式
3.启用IIS7上的CORS

但问题没有解决!

+2

是您需要启用它在你的API –

+0

@RahulSingh CORS由web.config中一个CORS问题已启用,问题是不解决 – Allahyar

+0

检查后在邮递员。 默认情况下/ token是获取mvc令牌的URL – Habeeb

回答

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); 
+0

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