【问题标题】:Angular 6 call localhost APIAngular 6 调用 localhost API
【发布时间】:2018-09-26 07:31:37
【问题描述】:

我试图在我的 Angular 6 应用程序中本地调用一个 api,api url 是 http://localhost/myapi 我添加了一个指向这个 url 的代理配置文件,但我得到了 404 运行我的应用程序时出错。

我的 proxy.config.json 文件:

{
  "/api/*":{
    "target":"http://localhost/myapi",
    "secure": false,
    "logLevel": "debug"
  }
}

package.json 文件:

"serve-dev": "ng serve --source-map=false --proxy-config proxy.config.json",

http.service.ts 文件:

export class HttpService{
     static serverApiUrl : string  = "/api/"
}

auth.service.ts 文件:

 this.http.get(HttpService.serverApiUrl+"site/check-auth")
            .map(response => {
                if(response['auth'] == 1) {
          return true;
                } else {
          this.router.navigate(['/auth'])
                    return false;
                }
            });

在控制台中我得到了这个:

http://localhost:4200/api/site/check-auth 

任何建议。

【问题讨论】:

  • 你是ng serve还是npm start
  • npm run serve-dev
  • 应用构建但请求返回 404 错误
  • 真正的api url是localhost/myapi/site/check-auth

标签: javascript angularjs api httpclient angular6


【解决方案1】:

看起来你需要rewrite the URL path,使用类似这样的东西:

{
    "/api": {
        "target": "http://localhost",
        "secure": false,
        "logLevel": "debug",
        "pathRewrite": {
            "^/api": "/myapi"
        }
    }
}

我已经从您的前缀中删除了/*,并添加了一个pathRewrite 部分。我相信您之前尝试代理到localhost/myapi/api/site/check-auth(带有额外的/api),应该用pathRewrite 部分剥离。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-15
    • 2019-09-19
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2021-09-11
    相关资源
    最近更新 更多