Angular: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

I know there are a lot of questions concerning CORS already but they don’t seem to answer my question.

So I have a client app written in Angular which will be used to create a mobile app (with Apache Cordova). The html files and JavaScript files will be loaded from the mobile device.
When I simulate that and I send requests to the REST API server I first got
“No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:82‘ is therefore not allowed access”.
So I added header(“Access-Control-Allow-Origin: *”); in my php REST API Server. I cannot specify a specific domain as the requests will come from the mobile devices.

Now I got to “A wildcard ‘*’ cannot be used in the ‘Access-Control-Allow-Origin’ header when the credentials flag is true.”

I finally found a solution but I’m not sure it is safe to keep it like this.

In my php REST API Server I added this:

if (isset($_SERVER['HTTP_ORIGIN'])) {
  header("Access-Control-Allow-Credentials: true");
  header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  header("Access-Control-Allow-Headers: *, X-Requested-With, Content-Type");
  header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT");
}

Please advise on this way of working. If it is not secure or no good at all, can you please tell me how to solve this issue?

Thanks a lot!

Node.js + Angular 2 RxJS Observabes & Change Detection – Best way to utilize Ajax Service with REST API?

I am very new to Angular 2 and do not know much about RxJS or the nature of observables. I am trying to achieve a certain functionality however, and am just looking for a guide to the right information I should be learning to achieve this and a more thorough knowledge.

I am working on a basic web application which is more of a test than anything, where several of my Angular 2 routed views will need to be asynchronously getting data from a REST API endpoint I built in Node.js.

Here is what I am trying to achieve:

When I route (with Angular) to site.com/messages there will be a view, whose component will be utilizing a service which is pulled in through a parent component’s providers array. I need this service to constantly get data from the API endpoint site.com/api/messages.

It seems to me that the most intuitive way to do this would be to have the the component that needs the data setup an http.get() on setInterval() when the component is initialized (ngOnInit life cycle hook). This will repeatedly poll the endpoint I need, so that it gets the data for the view which can use a structural directive to iterate through it or something like that.

Issue with this is I feel that it is a very primitive way to handle getting data. I would like to be using the newest and most effective and efficient way to do this. Unfortunately I am very new to Angular 2 and am not very familiar with some of the technologies and practices behind it. I have heard of and seen RxJS observables, Angular change detection, RxJS observable streams, and am wondering what the best way to learning these and what exactly will they buy me as far as asynchronous data fetching with an Angular 2 service. Any information as to how to utilize these technologies and how they all fit together would be great. Thanks

Angular2 Module Http for REST Services not found

When I’m using Meteor and Angular like it’s described in the tutorial there is no Angular2 Module called Http to user REST Services.

I used below tutorial from Meteor :
http://www.angular-meteor.com/tutorials/socially/angular2/bootstrapping

When I want to import:

import {Http, HTTP_PROVIDERS} from 'angular2/http';

and I start meteor, I get this Error Message:

[web.browser] client/app.ts (5, 36): Cannot find module ‘angular2/http’.

Rest request with angular2

Bonjour l’équipe, je suis nouvelle dans le dev en typescript sur angular2; j’ai déjà conçu une interface toute basique, j’aimerai à présent interagir avec mon serveur à distance, via une requête Rest. Je devrais normalement obtenir du json, mais en lançant mon fichier index.html, je ne reçois qu’un “loading…” et puis rien. Est ce que quelqu’un a déjà eu ce genre de problémes? voici le code de mon fichier app.component.ts

Translation

Hi team, I’m new in the Typescript team on Angular2. I still designed a basic Web UI and I would like now to interact with a remote server using a REST request. I should get some JSON content but when launching my index.html file, I only display a “loading…”. Does someone already have such problem? Here is the content of my app.component.ts file:

import {Component} from 'angular2/core';
import {Http} from "angular2/http";
import {getResponseURL} from "angular2/src/http/http_utils";
import {Response} from "angular2/http";


interface Requete {
    id: number;
    name: string;
}

@Component({
    selector: 'my-app',

    template: `<h1>{{title}}</h1>
           <h2>{{requete.name}} : Powerful environment</h2>
           <div><label>request id:</label>{{requete.id}}</div>
           <div>
                <label>enter request here:</label>
                <div><input [(ngModel)]="requete.name" placeholder="request"></div>
           </div>
           <form (submit)="onSubmit()">
               <input type="submit" value="OK" />
           </form>
          `
})

export class AppComponent {

    public title = 'GREAT LIVE';
    public requete: Requete = {
        id: 1,
        name: 'MDX'
    };

    onSubmit(){
        console.log("REQUETE:", this.requete);
    }

    constructor(private http: Http){
        http.get(`http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false`)
            .subscribe(getResponseURL => {
                console.log(getResponseURL.status);
                console.log(getResponseURL.headers);
                console.log(getResponseURL.json());
            });
    }
}

Error Handling Mechanism while Http Request (REST API) angular2

I am making some REST call (using HTTP request) in angular2.As depend on condition requests are of type GET,POST,PUT,DELETE.
Everything works fine for me i am using the below method to make request using seprate service file and class (component class) file.

* service.ts

PostRequest(url,data){
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');

this.requestoptions = new RequestOptions({
    method: RequestMethod.Post,
    url: url,
    body: JSON.stringify(data),
    headers: this.headers
})

return this.http.request(new Request(this.requestoptions))
    .map((res: Response) => {
        if (res) {
            if(res.status == 201){ 
                return [{ status: res.status, json: res.json }]    
            }
            else if(res.status != 201){ 
                return [{ status: res.status, json: null }]
            }
        }
        // i want to handle error here but how i don't know
    }); 
}
  • component_class.ts
this.base_path_service.PostRequest(url_postSection, data)
.subscribe(res=> {
   if (res[0].status == 201) {  //some stuff here..... }
});

Now come to question, my Question is

  • How can i handle error occured in the http,
  • i know next,error,oncomplete methods of subscribe but is it possible to handle the error at the time of mapping observable i.r
    return this.http.request(new Request(this.requestoptions))
    .map( //is it possible to handle error here instead at the time of subscribe)

  • i want to get notify to user depends on status code(201,200,204 etc…), so i want to write code once i.e at the time of .map instead of
    writing code agagin and again at the time of subscribe

    if any another approach is good for error handling while HTTP please post it as answer with example.

Integrate angular2-webpack-starter with NodeJS API REST

I would like to learn angular2 webpack materlias2 node…etc… I started using and modifying this boilerplate:
angular2-webpack-starter

Now I want to learn also nodejs as web server (with express framework, or whatever you suggest, an mysql ORM, etc…).

My question is: Now that I’ve my example project (coming from angular2-webpack-starter) where I’ve created a dummies ajax calls, how can I integrate my project with a API REST written in NodeJS?
Can you provide as simple example code?
And also, starting from the angular2-webpack-starter boilerplate, where is the best place where to put all the API rest server code?

Any other suggestion will be appreciated

Thank you very much

Web Service Rest with Angular2 'POST'

this is my Service Typscript where I have the method Json post

 import {Injectable, Inject} from "angular2/core";
    import {Http, Headers} from "angular2/http";
    import 'rxjs/add/operator/map';
    import {User} from "../User/User";


    @Injectable()
    export class loginService {

        constructor(@Inject(Http) private _http:Http) {
        }
        enter code here

        postJSON(){
            var json = JSON.stringify({v:"value",a:"3"}); // var creds = "username=" + "khalil" + "&password=" + 3;   .map(res=>res.text());
            var headers = new Headers();
            headers.append('Content-Type','application/json');
            return this._http.post('http://localhost:8080/connect',json,{
                    headers:headers
                })
                .map(res=>res.json());

        }

this is my component with subscribe

import {Component, Inject} from 'angular2/core';
import {Router} from "angular2/router";
import {loginService} from "./login.service";
import {HTTP_PROVIDERS, Http} from "angular2/http";
import {User} from "../User/User";


@Component({
    selector: 'login',
    templateUrl: '../dev/login/login.html',
    providers: [HTTP_PROVIDERS, loginService]
})

export class TestComponent {

    getData:string;

    postData:string;

    constructor(private _router:Router,
                @Inject(Http) http:Http,
                private _loginService:loginService) {


    }


    postJson(){
        this._loginService.postJSON().subscribe(
            data => this.postData = JSON.stringify(data),
            error => alert(this.postData + error),
            () => console.log("finished")
        );
    }
}        
        }

server side I work with spring 4

this is my controller

@RestController
@CrossOrigin()
public class HomeController {


    @RequestMapping(value = "/connect", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String connect(String v, String a) {
        int i = Integer.parseInt(a);
        if (v.equals("khalil") && i == 3) {
            System.out.println("----------------------***********************---------------------");
        } else {
            System.out.println("----------------------**** elseeeeee *******************---------------------");

        }
        return v+a;

    }
}

when I try to call a web service rest I get this error

 POST http://localhost:8080/connect 500 (Internal Server Error)(anonymous function)
 @ http.js:683Observable.subscribe 
@ Rx.js:11006Observable._subscribe
 @ Rx.js:11038Observable.subscribe 
@ Rx.js:11004loginComponent.postJson
 @ login.component.ts:63ChangeDetector_loginComponent_0.handleEventInternal 
@ viewFactory_loginComponent:415AbstractChangeDetector.handleEvent
 @ angular2.js:9568AppView.triggerEventHandlers
 @ angular2.js:10246(anonymous function)
 @ viewFactory_loginComponent:558(anonymous function)
 @ angular2.js:14068(anonymous function)
 @ angular2.js:13496ZoneDelegate.invoke 
@ angular2-polyfills.js:332NgZoneImpl.inner.inner.fork.onInvoke 
@ angular2.js:2111ZoneDelegate.invoke
 @ angular2-polyfills.js:331Zone.runGuarded 
@ angular2-polyfills.js:241NgZoneImpl.runInner
 @ angular2.js:2140NgZone.run
 @ angular2.js:13649outsideHandler 
@ angular2.js:13495ZoneDelegate.invokeTask
 @ angular2-polyfills.js:365Zone.runTask
 @ angular2-polyfills.js:263ZoneTask.invoke 
@ angular2-polyfills.js:431

thanks for helping me ^^

Rendering ActivePivot in a web page

I would like to retrieve data from activePivot’s cube by sending MDX with Rest request.
I tried to do it and I retrieved a json object then I parsed this json object to retrieve just specific information (look to the picture).

I had a look on this question : Can I connect ActivePivot to the tableau software?, but it is not complete.

Now I would like to render information whatever the request is, in a dynamic table in a web page. How can I do it?

enter image description here

Angular2 missing Set-Cookie in response from REST service

Goal

The goal is to call a remote login-service with HTTP Basic and receive the JSESSIONID for further usage.

Tested backend

So far I achieved the service call including a 200 response. My tests with restassured work smoothly and indicates that the JSESSIONID is properly provided by the login-service. The spring backend service is annotated with @CrossOrigin.

// assure we are not logged in
RestAssured.baseURI = "https://" + ip;
RestAssured.basePath = "/user";
Response responseA = post("/create"); // /user/create is a secured service
assertEquals(401, responseA.statusCode());

// log in and save the token
RestAssured.baseURI = "https://" + username + ":pass@" + ip; // http basic auth is used
RestAssured.basePath = "/user";
Response responseB = post("/login");
assertEquals(200, responseB.statusCode());

String jsessionId = responseB.getCookie("JSESSIONID");
// C50C28EA1F3ABBB76F0E4189A772A4E9

RestAssured.baseURI = "https://" + ip;
RestAssured.basePath = "/user";

// call a service without token or credentials --> 401
Response responseC = get("/id"); // /user/id is a secured service
assertEquals(401, responseC.statusCode());

// call a service with the token
RestAssured.sessionId = jsessionId;
Response responseD = get("/id");
assertEquals(200, responseD.statusCode());

The test is green.

Frontend problems

In our Angular2 frontend app we have a login page, whose submit button runs the following code through the onSubmit() method.

_url = "theLoginServiceUrl"

createAuthorizationHeader(username: string, password: string, headers:Headers) {
    headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
    // tried all of these, but they didn't fix the problem
    // headers.append('Access-Control-Allow-Origin', '*');
    // headers.append('Access-Control-Allow-Headers', '*');
    // headers.append('Access-Control-Allow-Methods', '*');
}

login (username: string, password: string) {
    let headers = new Headers();
    this.createAuthorizationHeader(username, password, headers);
    return this._http.post(this._url, "", {
        headers: headers
    });
}

onSubmit() {
    this.login(this.currentUser.username, this.currentUser.password)
        .subscribe((res) => {
                var headers = res.headers;
                console.log(headers); 
                // Headers {_headersMap: Map}
                // <entries>[3]
                // {"Pragma" => Array[1]}
                // {"Cache-Control" => Array[1]}
                // {"Expires" => Array[1]}

                var setCookieHeader = headers.get('Set-Cookie');
                console.log(setCookieHeader)
                // null
            }
        );
}

As you see from the comments I am not able to access Set-Cookie header. In the browser however I see the successful calls including the Set-Cookie header:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=58A072F2BB40A711CB42233CA4EB7BF6; Path=/; Secure; HttpOnly
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin
Access-Control-Allow-Credentials: true
Content-Length: 0
Date: Fri, 06 May 2016 10:43:21 GMT

Note that this all runs through HTTPS.

Frontend details:

  • "typescript": "^1.7.5"
  • "angular2": "2.0.0-beta.7"

Question:

Why can’t I access the Set-Cookie within my Angular2 code? What do I have to change?

Angular 2 with SharePoint 2013 web part development

I want to develop web part for SharePoint 2013 farm solution using WCF custom Rest Services that will get data from content database using server object model and to consume those services in web part I have to use Angular 2. Can anyone tell me how to use Angular 2 in share point 2013 for web part development.