使用令牌错误的登录身份验证Access-Control-Allow-Origin'

时间:2019-03-01 06:33:38

标签: asp.net-mvc angular

 userAuthentication(userName, password) {

        let headers = new Headers();
        var data = "username=" + userName + "&password=" + password + "&grant_type=password";
        // var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
        headers.append('Content-Type', 'application/x-www-urlencoded');
        headers.append('Access-Control-Allow-Origin', '*');
        headers.append('No-Auth','True');
        
        headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT');
        return this.http.post(environment.apiUrl + 'token', data, { headers: headers  })
        .pipe(map(data => data.json()),
        catchError((error: any) => {
          throw error;
        }));
      }
    }

我在客户端使用angular,在服务器端使用asp.net mvc。我面临一个错误Access-Control-Allow-Origin

1 个答案:

答案 0 :(得分:0)

您收到的错误是因为您没有访问API所需的权限 将此行添加到您的API代码中

您必须先安装cors

Install-Package Microsoft.AspNet.WebApi.Cors

在您的API中添加此行之后

 config.EnableCors();

“ config”是指httpconfiguration类

您现在可以访问您的API