【问题标题】:Angular 2 Failed to execute open on XMLHttpRequest: Invalid URLAngular 2 无法在 XMLHttpRequest 上执行打开:无效的 URL
【发布时间】:2017-07-16 14:46:35
【问题描述】:

我正在尝试调用服务,它在 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);
}));

帮助:(谢谢

【问题讨论】:

  • 如果是192.168.. 类型的url,您是否尝试在其前面添加http://https://?如果是这样,您正在执行跨域请求,并且需要在服务器端启用 CORS 选项。
  • 你真是个天才,谢谢!我是新手。
  • 哈哈,没问题。我会提供它作为答案。

标签: angular typescript xmlhttprequest jwt


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果你使用 localhost,那么只在你的 localhost 之前使用 http://

    【讨论】:

      【解决方案3】:

      在我的情况下,我能够通过从客户端而不是服务器端修复我的 http 请求的 url 来解决这个问题,因为在 localhost 中缺少 http:// 时提到了 echonax。

      我的问题是,在我的请求中this.http.get(this.domain + '/api/prod/' + id).map(res => res.json())

      我在api 的正面缺少/。应该是/api

      【讨论】:

        【解决方案4】:

        可能的情况:

        1. 你的api格式不对,应该是例如:http:localhost:8080/

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

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

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

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

          李>

        【讨论】:

          【解决方案5】:

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

          @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】:

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

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

            【讨论】:

              【解决方案7】:

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

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

              "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 复制到您的编辑器并使用右箭头从左到右导航。在所示位置,您必须再按一次右箭头键。

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

              【讨论】:

                【解决方案8】:

                在我的情况下,我通过在我的 api 之前添加“/”解决了这个问题 最初是const url = environment.api + 'api/relay'; 我改成const url = environment.api + '/api/relay';

                它有效。

                【讨论】:

                  【解决方案9】:

                  我在 URL 示例中将 ' 更改为 "

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

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

                  【讨论】:

                    猜你喜欢
                    • 2017-08-15
                    • 2019-12-01
                    • 2019-04-27
                    • 2020-07-18
                    • 1970-01-01
                    • 2019-09-25
                    • 1970-01-01
                    • 2018-01-06
                    • 2015-12-28
                    相关资源
                    最近更新 更多