Search code examples
angularnativescripthttpclient

Http.get request returns error while working fine with other api sample


I am trying to get a token in my Nativescript mobile app from locally installed moodle api. I have confirmed that api request is working okay, as well as the request code. (value returns as expected when I used jsonplaceholder data) I read about CORS issue in other questions and tried to enable it on my local server (apache2) but nothing worked so far.

LoadModule headers_module libexec/apache2/mod_headers.so in httpd.conf was already enabled and I added,

<Directory "/Users/lucy/Sites/">
AllowOverride All
Header set Access-Control-Allow-Origin "*" 
</Directory>

I've tested mod_header to see whether the module is active referring (Enable mod_header in apache in Mac OS X for CORS) , by

$ httpd -M |grep header

and it returns

AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist
headers_module (shared)

Not sure if it is related to the issue. I checked the source file (token.php) in moodle and this has,

// Allow CORS requests.
header("Access-Control-Allow-Origin: *");

which should allow access from other servers (if I understood it correctly). Any help would be appreciated. Thanks in advance.

login.service.ts

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Login } from "../login/login";

@Injectable()
export class LoginService{

    constructor (private http: HttpClient) {}

    getToken(): Observable<Login[]> {    
        return this.http.get<Login[]>("http://mywebsite.dev.com/login/token.php/");
        // return this.http.get<Login[]>("https://jsonplaceholder.typicode.com/todos/1"); //test api working fine
    }
}

login.ts

export class Login {
    token: string;
    privatetoken: string;
    // userId: number;
    // id: number;
    // title: string;
    // completed: boolean;
}

login.component.ts

import { Component, OnInit } from "@angular/core";
import { RadSideDrawer } from "nativescript-ui-sidedrawer";
import * as app from "tns-core-modules/application";

import { LoginService } from './login.service';
import { Login } from '../login/login';
import { Observable } from "rxjs";

@Component({
    selector: "Login",
    templateUrl: "./login.component.html"
})
export class LoginComponent implements OnInit {

    public token: Login[];    

    constructor(private loginService: LoginService) {
        // Use the component constructor to inject providers.
    }

    ngOnInit(): void {

        this.loginService.getToken().subscribe(token => {
            this.token = token;


        });
   }
}

error message

"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": "http://mywebsite.dev.com/login/token.php/",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://mywebsite.dev.com/login/token.php/: 0 Unknown Error",
"error": {
"line": 147190,
"column": 38,
"sourceURL": "file:///app/vendor.js",
"originalStack": "ZoneAwareError(file:///app/vendor.js:147190:38)\nat file:///app/vendor.js:91152:37\nat UIApplicationMain([native code])\nat run(file:///app/vendor.js:85234:26)\nat file:///app/vendor.js:142544:26\nat file:///app/vendor.js:142445:38\nat file:///app/vendor.js:142425:26\nat file:///app/bundle.js:300:144\nat ./main.ts(file:///app/bundle.js:305:34)\nat __webpack_require__(<…>

Solution

  • I solved the issue. This wasn't CORS or header issue, it was about connecting localhost API from a local app. I had to use ip address instead of domain name to connect its API. After changing the get address it's working okay now.

    return this.http.get<Login[]>("http://192.168.20.9/login/token.php");
    

    Cannot connect to localhost API from Android app This answer helped me figure out the problem.