Search code examples
angularjsxmlhttprequest

connect to API with X-Auth-Token when running local


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?


Solution

  • 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