Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Failed to execute open on XMLHttpRequest: Invalid URL

I'm trying to call a service, it's works in DHC, but when I try to call in my angular 2 project, it crash, the method request is POST, receive an object from body who has a email and password, and the response is a token, that I will use in the entire project for authorization.

Here is my code.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, Request ,RequestOptions ,RequestMethod } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginService {
      constructor(private http:Http) { 
      }

  getToken(){
    var baseUrl = "xxx.xxx.x.xxx:xxxx/project/v1/admin/login";
    var headers = new Headers();
    headers.append("Content-Type", 'application/json');
    var options = new RequestOptions({ headers: headers });
    var objeto = {'email': 'xxxxxx', 'pass':'xxxx' } 
    var body2 = JSON.stringify(objeto);
    var xhr = new XMLHttpRequest();
    return this.http
       .post(baseUrl, body2, options)
       .map((response: Response) => response.json())
       .subscribe(
           data => console.log('Success uploading the opinion '+ data, data),
           error => console.error(`Error: ${error}`)
       );
  }
}

I try to implement XMLHttp Request call from angular 2, but the error is the same, I don't know if I can using it in angular 2, here is the method

return Observable.fromPromise(new Promise((resolve, reject) => {
  //  let formData: any = new FormData();     
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                resolve(JSON.parse(xhr.response));
            } else {
                reject(xhr.response);
            }
        }
    }
    xhr.open("POST", baseUrl, true);
    xhr.send(body2);
}));

Help :( and thank you

like image 880
Marlaurita Avatar asked Feb 25 '17 20:02

Marlaurita


3 Answers

If it's a 192.168.. type of url you should add a http:// or https:// in front of it. And you may need to enable CORS options on server side.

like image 158
eko Avatar answered Oct 17 '22 14:10

eko


In my case, I was able to solve it by fixing the url for my http request from the client side instead of the serverside as echonax mentioned from missing http:// from localhost.

My issue was, in my request this.http.get(this.domain + '/api/prod/' + id).map(res => res.json())

I was missing a / from the front side of api. It should be /api

like image 21
eyoeldefare Avatar answered Oct 17 '22 16:10

eyoeldefare


if you use localhost then only use http:// before your localhost

like image 2
Nagender Chauhan Avatar answered Oct 17 '22 16:10

Nagender Chauhan