Angular 2无法在XMLHttpRequest上执行打开:无效的URL

时间:2017-02-25 20:20:23

标签: angular typescript xmlhttprequest jwt

我正在尝试调用服务,它可以在DHC中运行,但是当我尝试调用我的angular 2项目时,它崩溃了,方法请求是POST,从具有电子邮件和密码的正文接收对象,并且响应是一个令牌,我将在整个项目中使用以进行授权。

这是我的代码。

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}`)
       );
  }
}

我尝试从angular 2实现XMLHttp Request调用,但错误是一样的,我不知道我是否可以在angular 2中使用它,这里是方法

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);
}));

帮助:(谢谢

8 个答案:

答案 0 :(得分:31)

如果它是192.168..类型的网址,您应该在其前面添加http://https://。您可能需要在服务器端启用CORS选项。

答案 1 :(得分:9)

在我的情况下,我能够通过从客户端修改我的http请求的url来解决它,而不是像http://localhost丢失的this.http.get(this.domain + '/api/prod/' + id).map(res => res.json())中提到的echonax那样修复服务器端。

我的问题是,在我的请求中/

我在api的正面错过了/api。它应该是{{1}}

答案 2 :(得分:1)

如果您使用localhost,则只需在localhost

之前使用http://

答案 3 :(得分:1)

如果上述方法都不起作用,请查找字符串中的隐藏字符。

所以就我而言,这很神秘。我从网站上复制了我的网址,但一个隐藏字符也随字符串一起复制了,这在视觉上是不可见的。

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

不敢相信?在浏览器控制台中试试这个

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

字符串中有一个神秘的字符:

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

要感受一下,请将 url 复制到您的编辑器并使用向右箭头从左到右导航。在显示的位置,您必须多按一次右箭头键。

为了记录,隐藏字符在这个引号内:'​'

答案 4 :(得分:0)

可能的情况:

  1. 您的api格式不正确,例如: http:localhost:8080 /

  2. 在您的api中,您没有启用 CORS ,因此它不接受您的请求

  3. 您最后缺少了 / 字符,在我的情况下,我有 http:localhost:8080 ,并且由于缺少<最后是strong> /

  4. 您使用的是http而不是https或相反的

  5. 您在api中创建的凭证请求不正确,这可能是由于前端部分的请求代码中出现错误(角度,反应等)

答案 5 :(得分:0)

可能发生此错误的另一个上下文是使用拦截器设置基本路径时。类似于以下内容:

@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);
  }
}

如果在向http客户端提供对完整http / https URL的请求时触发此拦截器,则它将构造无效的URL。

答案 6 :(得分:0)

对于那些尝试使用POSTMAN并收到此错误的人。请检查他们使用的网址。复制该URL并粘贴在记事本中进行检查。

就我而言,当我从其他地方复制我的方法名称时,上面有空格,而邮递员没有正确显示我的名字。一旦我删除了空间,它就可以正常工作。

答案 7 :(得分:0)

就我而言,我通过在 api 之前添加“/”解决了这个问题 最初是a = [1, 2, 3, 4, 5] i = 0 print(i) print(a[i] + 3) print(a) a[i], a[a[i] + 3] = a[a[i] + 3], a[i] # this shows error even tho below is the same and does not #a[0], a[4] = a[4], a[0] print(a) 我改为const url = environment.api + 'api/relay';

它有效。