无法使用HttpClient以角度使用代理配置和解决方案进行发布请求

时间:2017-10-24 13:42:34

标签: angular httpclient

虽然我试图在HttpClient中发布帖子请求但得到以下错误,而其他客户端给出了正确的响应。与angular 1 $http服务相同的服务正在按预期工作。

尝试了多种方式,但post和get方法都没有工作。 我正在使用我已配置proxy.config.json

的angular-cli
{
    "/api/*":{

        "target":"http://10.104.40.14:8290/my_app",
        "secure":false,
        "logLevel":"debug"
    }
}

//错误代码

 zone.js:2933 POST http://localhost:4200/api/security/login 401 (Unauthorized)
     <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>Error 401 Unauthorized</title>
    </head>
    <body><h2>HTTP ERROR 401</h2>
    <p>Problem accessing /de_prp/error. Reason:
    <pre>    Unauthorized</pre></p>
    </body>
    </html>

这是我的auth.service.ts文件

    import { Injectable, OnInit } from '@angular/core';

   import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
        import { RequestOptions, Headers } from '@angular/http';
        import { URLSearchParams } from '@angular/http';
        @Injectable()
        export class AuthService implements OnInit {
          constructor(private http: HttpClient) { }

          ngOnInit(): void {

          }


          login(username, password, rememberMe) {
            console.log(username, password, rememberMe);

            //const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
            const body = JSON.stringify({ username: username, password: password });
            const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
            this.http.post("/api/security/login", body, { headers: headers }).subscribe(
              res => {
                console.log(res);
              },
              (err: HttpErrorResponse) => {

                console.log(err.error);
                console.log(err.name);
                console.log(err.message);
                console.log(err.status);
              }
            )
          }
          logout() {

            this.http.get("/api/auth/logout").subscribe(
              res => {
                console.log(res);
              },
              (err: HttpErrorResponse) => {

                console.log(err.error);
                console.log(err.name);
                console.log(err.message);
                console.log(err.status);
              }
            );
          }
        }

解决方案:最后通过下面给出的proxy.config.json中的条目解析 &#34; pathRewrite&#34;:{&#34; ^ / api&#34; :&#34;&#34;}所以最终的json文件是

{
    "/api/*":{

        "target":"http://10.104.40.14:8290/my_app",
        "secure":false,
        "pathRewrite": {"^/api" : ""}
    }
}

1 个答案:

答案 0 :(得分:1)

尝试以这种方式撰写您的帖子请求:

login(username, password, rememberMe)) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    //You can append here whatever you like in your headers;
    headers.append(username, password);

    options: RequestOptions = new RequestOptions(headers);

    this.http.post(/api/security/login, options)
      .suscribe(res => res.json())
  }

401是来自处理请求的服务器的错误。如果服务器正在获取您的请求标题,您需要查看。

关于您的代理配置,您可以执行以下操作:

{ "/api": { "target": "yourUrl.com", 
             "secure": false, 
             "pathRewrite": {"^/api" : ""} 
          }
}

pathRewrite选项会从您的网址中删除api