代理配置在 angular 6 中不起作用

Proxy configuration is not working in angular 6

我有 metronic_v5.5.2 Angular 版本,我正在尝试将其 angular 版本与我的后端集成 API.

由于我对这一切还很陌生,现在的问题是我的代理配置没有按照我的预期工作。

以下是proxyconfig.json文件

的代码
{
    "/api": {
        "target": "https://localhost:5001",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

图像显示请求正在路由到 URL "https://localhost:5001/api/auth/login" POST /api/auth/login -> https://localhost:5001

但是在浏览器的控制台中,这个请求实际上是路由到 URL http://localhost:4200/api/auth/login which return 401 error. I am unable to route on clicking of button to the url: https://localhost:5001/api/auth/login

以下是HTML代码

<!--begin::Form-->
<form class="m-login__form m-form" name="form" (ngSubmit)="f.form.valid && submit()" #f="ngForm" novalidate>
    <div class="form-group">
        <mat-form-field>
            <mat-label>Email</mat-label>
            <input matInput type="email" name="email" placeholder="Email address" autocomplete="off" [(ngModel)]="model.email" #email="ngModel" email="true" required>
        </mat-form-field>
    </div>
    <div class="form-group">
        <mat-form-field>
            <mat-label>Password</mat-label>
            <input matInput minlength="4" type="password" name="password" placeholder="Password" autocomplete="off" [(ngModel)]="model.password" #password="ngModel" required>
        </mat-form-field>
    </div>
</form>
<!--end::Form-->

<!--begin::Action-->
<div class="m-login__action m-login__action--fit">
    <a href="javascript:;" (click)="forgotPasswordPage($event)" class="m-link">
        <span translate="AUTH.GENERAL.FORGOT_BUTTON">Forgot Password?</span>
    </a>
    <m-spinner-button [options]="spinner" (click)="submit()">{{'AUTH.LOGIN.BUTTON' | translate}}</m-spinner-button>
</div>

以下是login.component.ts代码

submit() {
        this.spinner.active = true;
        if (this.validate(this.f)) {
            this.authServiceDb.logindb(this.model).subscribe(response => {
                    this.router.navigate(['/']);
                    this.alertify.success('Logged In Successfully');
                    this.spinner.active = false;
                    this.cdr.detectChanges();
            }, error => {
                this.alertify.error(error);
            });
        }
    }

函数导出的 authdb 代码 class 给出打击,编辑

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '../../../node_modules/@angular/http';
import { map, catchError } from 'rxjs/operators';
import { throwError } from '../../../node_modules/rxjs';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';

@Injectable({
    providedIn: 'root'
})
export class AuthdbService {
    baseUrl = 'api/auth/';
    userToken: any;
    decodedTokenn: any;
    jwtHelper: JwtHelper = new JwtHelper();
    constructor(private http: Http) { }
public logindb(model: any) {
    return this.http.post(this.baseUrl + 'login', model, this.requestOptions()).pipe(map((response: Response) => {
      const user = response.json();
      if (user) {
        localStorage.setItem('token', user.tokenString);
        this.decodedTokenn = this.jwtHelper.decodeToken(user.tokenString);
        this.userToken = user.tokenString;
      }
    })).pipe(catchError(this.handleError));
  }
  register(model: any) {
    return this.http.post(this.baseUrl + 'register', model, this.requestOptions()).pipe(catchError(this.handleError));
  }
  loggedIn() {
    return tokenNotExpired('token');
  }
  private requestOptions() {
    const headers = new Headers({
      'Content-type': 'application/json'});
    return new RequestOptions({headers: headers});
  }
  private handleError(error: any) {
    const applicationError = error.headers.get('Application-Error');
    if (applicationError) {
      return throwError(applicationError);
    }
    const serverError = error.json();
    let modelStateErrors = '';
    if (serverError) {
      for (const key in serverError) {
        if (serverError[key]) {
          modelStateErrors += serverError[key] + '\n';
        }
      }
    }
    return throwError(
      modelStateErrors || 'Server Eroor'
    );
  }
}

在我的 package.json 中,我有以下代码

{
    "name": "default",
    "version": "0.0.0",
    "license": "MIT",
    "scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxyconfig.json",
        "build": "ng build --prod",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
    },
    "private": true,
    "dependencies": {
        "@angular/animations": "^6.1.0",
        "@angular/cdk": "^6.4.0",
        "@angular/common": "^6.1.0",
        "@angular/compiler": "^6.1.0",
        "@angular/forms": "^6.1.0",
        "@angular/http": "^6.1.0",
        "@angular/platform-browser": "^6.1.0",
        "@angular/platform-browser-dynamic": "^6.1.0",
        "@angular/platform-server": "^6.1.0",
        "@angular/router": "^6.1.0",
        "@kolkov/angular-editor": "^0.10.3",
        "@ng-bootstrap/ng-bootstrap": "^2.2.0",
        "@ngx-loading-bar/core": "^2.1.1",
        "@ngx-translate/core": "^10.0.2",
        "@types/lodash": "^4.14.112",
        "alertifyjs": "^1.11.1",
        "angular-in-memory-web-api": "^0.6.0",
        "angular2-jwt": "^0.2.3",
        "chart.js": "^2.7.2",
        "classlist.js": "^1.1.20150312",
        "core-js": "^2.5.7",
        "hammerjs": "^2.0.8",
        "lodash": "^4.17.10",
        "material-design-icons": "^3.0.1",
        "ng2-charts": "^1.6.0",
        "ngx-auth": "4.0.0",
        "ngx-highlightjs": "^2.0.4",
        "ngx-perfect-scrollbar": "^6.2.0",
        "ngx-permissions": "^5.0.0",
        "object-path": "^0.11.4",
        "rxjs-compat": "^6.2.2",
        "rxjs-tslint": "^0.1.5",
        "web-animations-js": "^2.3.1",
        "zone.js": "^0.8.26"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^0.7.0",
        "@angular/cli": "^6.0.8",
        "@angular/compiler-cli": "^6.1.0",
        "@angular/core": "^6.1.0",
        "@angular/language-service": "^6.1.0",
        "@angular/material": "^6.4.0",
        "@angular/material-moment-adapter": "^6.4.0",
        "@types/jasmine": "^2.8.8",
        "@types/jasminewd2": "^2.0.3",
        "@types/node": "^10.5.2",
        "codelyzer": "^4.4.2",
        "jasmine": "^3.1.0",
        "jasmine-core": "^3.1.0",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~2.0.4",
        "karma-chrome-launcher": "^2.2.0",
        "karma-coverage-istanbul-reporter": "^2.0.1",
        "karma-jasmine": "^1.1.2",
        "karma-jasmine-html-reporter": "^1.2.0",
        "moment": "^2.22.2",
        "protractor": "^5.3.2",
        "rxjs": "^6.2.2",
        "ts-node": "^6.0.3",
        "tslint": "~5.9.1",
        "typescript": "2.7.2"
    }
}

你说你是新手,我先简单的解释一下。

当您调用 http.post 时,第一个参数是将联系的 url。所以:

this.http.post(this.baseUrl + 'login', ...

会变成

this.http.post('api/auth/login', ...

因为您设置了 baseUrl 并添加了 'login':

baseUrl = 'api/auth/';

但是您的代码没有说明要使用哪个协议(http 或 https),也没有说明要调用哪个 domain:port(例如 http://mydomain:port/api/auth/login)。

因此 Angular 将默认为 'http' 以及 IT 使用的域和端口,即 localhost:4200。所以你的请求变成:

http://localhost:4200/api/auth/login

这就是您在控制台中看到它的原因。 Angular 完全忽略了您的代理文件。 我认为原因要么是名称,要么是位置(它通常应该在您项目的根文件夹中),或者您没有告诉 Angular加载它。

您需要告诉 Angular 在它启动时实际使用它。所以在 package.json 你需要这样的东西:

"start": "ng serve --proxy-config proxyconfig.json"

这告诉 Angular-CLI,当您使用 npm run start(或只是 npm start)命令启动应用程序时,它应该从 [=58] 加载代理数据=]根文件夹中的文件。

我也建议阅读 this tutorial

此外,我认为您的代理配置中缺少 /*

{
    "/api/*": {
        "target": "http://localhost:5001",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

我遇到了同样的问题,向服务目标添加 proxyConfig 选项就可以了。

转到 angular.json -> 在服务中添加 key:value 对 "proxyConfig": "proxy.conf.json"

像这样-

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "proxy.conf.json"
    },

顺便说一句,我从 here

那里得到了这个

我花了几个小时来修复 POST /api/auth/login 到 https://localhost:5001 的错误路由,这在您提供的图像中。

以下配置修复了 POST /api/auth/login 到 https://localhost:5001/api/auth/login.

的路由
{
    "/api": {
        "target": "https://localhost:5001/api",
        "changeOrigin": true,
        "logLevel": "debug",
        "pathRewrite": { "^/api" : "" }
    }
}

为 ng serve 添加“--ssl”参数:

"start": "ng serve --proxy-config proxyconfig.json --ssl",

因为您想建立安全连接:

"target": "https://localhost:5001",

来源: https://www.devdungeon.com/content/how-serve-angular-locally-over-https

要在 Angular 中配置代理,请按照以下步骤操作 -

步骤 1。在存在 package.json 文件的 angular 根文件夹中创建“proxy.conf.json”并添加以下代码 -

{
  "/api/*": {
    "target": "http://xxx.xxx.xxx.xxx:80/api/",  // API URL or any URL for Proxy
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

步骤 2。然后更新 angular.json 文件,在 architect -> serve -> builder -> options -

添加 属性 "proxyConfig" 属性
"projects": {
        ...
        "angularPracticeProj": {
                "projectType": "application",
                "schematics": {},
                ...
                "architect": {
                        ...
                        "serve": {
                                ...
                                "builder": "@angular-devkit/build-angular:dev-server",
                                  "options": {
                                    "browserTarget": "angularPracticeProj:build",
                                    "proxyConfig": "proxy.conf.json"        <==== angular proxy
                                  },
                                ...
                                }
                        ...
                        }
                    }
            }
            
        

如果您使用的是 NodeJS / ExpressJS REST API 然后从您加载 express 的 nodejs-

更新 app/root 文件

步骤 3(可选)。在 nodejs 或 ExpressJS 根文件中 - app root 被定义添加下面的代码 -

const app = express();
            // angular app set as start
            app.use(express.static(process.cwd() + "/../dist/angularPracticeProj/")); <= angular project's published/dist index file path
            app.get('/', (req, res) => {
            res.sendFile(process.cwd() + "/../dist/angularPracticeProj/index.html")   <= angular project's published/dist index file path
    });

我的 Angular 基础 url 应用程序也出现了同样的问题,我通过为 [=23= 添加参数得到了解决方案].

我们需要通过添加 --base-href=/your- 在 'start' 命令中更改 package.json 来指定 Angular 应用程序使用基础 url应用-url/

    "start": "ng serve --proxy-config proxyconfig.json --deploy-url=/your-application-baseurl/ --base-href=/your-application-baseurl/"

"Package.json" 加完后就是

    {
"name": "default",
"version": "0.0.0",
"license": "MIT",
"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxyconfig.json --deploy-url=/your-application-baseurl/ --base-href=/your-application-baseurl/",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
},