如何从角度7向键盘锁发出发布请求

时间:2019-03-12 13:36:53

标签: javascript cors angular7 keycloak

我已将密钥斗篷与我们的应用程序集成在一起。我需要在angular 7中对keycloak进行后期调用,但会引发CORS策略错误。 OPTIONS请求没有任何问题,但实际的发布请求将收到CORS错误。当我用Java脚本编写相同的帖子时,效果很好。

Angular 7 code:
-----------------
getResources() {
        const url = 'http://localhost:8080/auth/realms/Test_Anusha/protocol/openid-connect/token';
        const token = this.keycloakService.getKeycloakInstance().token;
        const httpOptions = {
            headers: new HttpHeaders()
                .append('Content-Type', 'application/x-www-form-urlencoded')
                .append('Authorization', 'bearer ' + token)
                .append('Access-Control-Allow-Origin', '*')
                .append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
        };
        const payload = {
            'grant_type': 'urn:ietf:params:oauth:grant-type:uma-ticket',
            'response_mode': 'permissions',
            'audience': 'enliven-gui',
            'permission': 'EIS'
        };
        try {
            console.log(url);
            console.log(JSON.stringify(payload));
            console.log(JSON.stringify(httpOptions));
            return this.http.post(url, JSON.stringify(payload), httpOptions).subscribe(res => {
                console.log('res', res);
              }, (err) => {
                console.log(err);
              }
           );
        } catch {
            console.log('error');
        }
    }

Java script code:
-------------------

getResources(tokenEndpint, token, clientId, resources) {
        token = this.keycloakService.getKeycloakInstance().token;
        const request = new XMLHttpRequest();
        request.open('POST', tokenEndpint, false);
        request.setRequestHeader('Authorization', 'Bearer ' + token);
       request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        let response;
        request.onreadystatechange = function () {
            if (request.readyState === 4) {
                if (request.status >= 200 && request.status < 300) {
                    response = JSON.parse(request.responseText);
                } else if (request.status === 403) {
                    console.log('Authorization request was denied by the server.');
                    return null;
                } else {
                    console.log('Could not obtain authorization data from server.');
                    return null;
                }
            }
        };
        this.params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&response_mode=permissions&audience=' + clientId;
        if (Array.isArray(resources)) {
            for (let i = 0; i < resources.length; i++) {
                this.params = this.params + '&permission=' + resources[i];
            }
        }
        request.send(this.params);
        return response;
    }

使用Java脚本代码可以正常工作,但不能使用angular 7代码。 我找不到问题所在。请多多帮助。

0 个答案:

没有答案