29

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

3
  • 1
    If it's a 192.168.. type of url did you try to add a http:// or https:// in front of it? And if so, you're doing a cross domain request and need to enable CORS options on server side. Commented Feb 25, 2017 at 20:27
  • You are a genious, thank you! I'm new on this. Commented Feb 25, 2017 at 21:10
  • 1
    Haha, no problem. I'll provide it as an answer. Commented Feb 25, 2017 at 21:11

10 Answers 10

49

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.

Sign up to request clarification or add additional context in comments.

Comments

21

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

Comments

2

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

Comments

1

Another context when this error might happen is when using interceptors to set a base path. Something like the following:

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {

  constructor(private logger: LoggingService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // one way is to except / include only some urls by checking request.url

    const clonedRequest = request.clone({
      withCredentials: true
    });

    // this.logger.logTrace("Sending with credentials request: ", request.urlWithParams);
    return next.handle(clonedRequest);
  }
}

If this interceptor fires when a request to a full http/https url is provided to the http client, it will construct an invalid URL.

Comments

1

If none of the said methods work, look for hidden characters in your string.

So in my case this was mysterious. I copied my url from a website but a hidden character also copied with the string, which is not visually visible.

"http://localhost:3000​/addresses​/create" // bad url
"http://localhost:3000/addresses​/create" // good url

Can't believe? Try this in the browser console

"http://localhost:3000​/addresses​/create" === "http://localhost:3000/addresses​/create"
// => false

There is a mysterious character right here in the string:

"http://localhost:3000​/addresses​/create"
//                    ^==> we have a hidden character here.

To feel it, copy the url to your editor and use right arrow to navigate from left to right. At the shown position, you have to press the right arrow key one extra time.

For record, the hidden character is inside this quotes: '​'

Comments

0

Possible scenarios:

  1. Your api format is incorrect, it should be for example: http:localhost:8080/

  2. In your api you don't have CORS enabled, so it is not accepting your requests

  3. You have missing the / character at the end, in my case I had http:localhost:8080 and wasn't working because of the missing / at the end

  4. You are using http instead of https or the opposite

  5. You are creating the request for your credentials in the api incorrectly, this can be caused for errors in the code of the request from the frontend part (angular, react, ...)

Comments

0

For those people, who is trying to use POSTMAN and getting this error. please check the URL they are using. Copy that URL and paste in notepad to check.

In my case when I was copying my method name from some other place, it had space on it and postman was not showing me correctly. Once I removed space, it worked fine.

Comments

0

In my case i solved this issue by adding the '/' before my api initially it was const url = environment.api + 'api/relay'; i changed to const url = environment.api + '/api/relay';

and it works.

Comments

0

Well I changed ' to " in the URL example.

'GET', environment.apiEndpoint + '/xxx/api/v1/xxx'` 

to

"GET", environment.apiEndpoint + "/xxx/api/v1/xxx"

Comments

0

In my case it was using Axios, and the method name had a blank space:

method: 'POST '

I just had to delete the blank space:

method: 'POST'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.