0

I'm in Angular 2 trying to connect to an API where eI do not have access server side. I know this API and token are ok works As I converting an existing PHP app to Angular.

Here is myapp.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DxdService {

    private apiUrl = 'https://path/to/my/api/';

    constructor(private _http: Http){

    }

    createAuthorizationHeader(headers: Headers) {
        headers.append('X-Auth-Token','myvalidkey'); 
    }

    getValueFromApi(){
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this._http.get(this.apiUrl, headers)
        .map(res => res.json());
    }
}

This return invariably

GET https://path/to/my/api/ 401 (Unauthorized)

XMLHttpRequest cannot load https://path/to/my/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The response had HTTP status code 401.

What I can't figure out here is, did the way I set my headers x-auth-token is wrong, or did I fight agains the Access-Control-Allow-Origin CORS issue.

Considering I can't access server side to change Access-Control-Allow-Origin header response, if the way I set my headers is right, how can I keep developing locally?

Benoit
  • 374
  • 4
  • 20

1 Answers1

0

You won't be able to fix this issue from a Frontend perspective, you need to access the server to make the proper adjustments and making it accesible from your Angular application

You can try implementing JSONP as the method in your request. Just keep in mind that JSONP only works with GET

$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

You can find more answers related to this issue here

Community
  • 1
  • 1
  • Thanks, as I can't access the server where my REST API is, the link you provide gave me an idea, and put me on a alternative way where I will quickly create a temporary PHP script on server I can control to return me the desired JSON data. – Benoit Jan 29 '17 at 12:10
  • i think it is angular 1 syntax – dimson d Mar 01 '17 at 19:37