Angular 8-将API URL更改为用于登录身份验证的本地服务器

问题描述 投票:0回答:1

我目前正在按照https://thinkster.io/tutorials/building-real-world-angular-2-apps/intercept-and-manipulate-http-requests中的指南创建一个Angular 8应用程序,用户可以在其中注册,创建帖子,查看全局帖子(如帖子)并关注其他用户。

本教程提供了一个实时API服务器,该服务器在https://conduit.productionready.io/api运行,以使应用程序可以发出请求-这为应用程序提供了使用该教程的其他用户的帖子。这是我克隆并定制的仓库的github链接:https://github.com/gothinkster/angular-realworld-example-app#making-requests-to-the-backend-api

但是,我想使用自己的本地服务器(localStorage?)测试我的应用并创建用户并自行发布。稍后,我将连接此API与我的Java / Spring代码和PostgreSQL数据库进行通信。

这是我的environment.ts文件的外观:

export const environment = {
  production: false,
  api_url: 'https://conduit.productionready.io/api'
};

这就是我的api.service.ts文件的样子:

    import { Injectable } from '@angular/core';
    import { environment } from '../../../environments/environment';
    import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
    import { Observable ,  throwError } from 'rxjs';

    import { JwtService } from './jwt.service';
    import { catchError } from 'rxjs/operators';

    @Injectable()
    export class ApiService {
      constructor(
        private http: HttpClient,
        private jwtService: JwtService
      ) {}

      private formatErrors(error: any) {
        return  throwError(error.error);
      }

      get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
        return this.http.get(`${environment.api_url}${path}`, { params })
          .pipe(catchError(this.formatErrors));
      }

      put(path: string, body: Object = {}): Observable<any> {
        return this.http.put(
          `${environment.api_url}${path}`,
          JSON.stringify(body)
        ).pipe(catchError(this.formatErrors));
      }

      post(path: string, body: Object = {}): Observable<any> {
        return this.http.post(
          `${environment.api_url}${path}`,
          JSON.stringify(body)
        ).pipe(catchError(this.formatErrors));
      }

      delete(path): Observable<any> {
        return this.http.delete(
          `${environment.api_url}${path}`
        ).pipe(catchError(this.formatErrors));
      }
    }

而且,以防万一,这是我的user.service.ts文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable ,  BehaviorSubject ,  ReplaySubject } from 'rxjs';

import { ApiService } from './api.service';
import { JwtService } from './jwt.service';
import { User } from '../models';
import { map ,  distinctUntilChanged } from 'rxjs/operators';


@Injectable()
export class UserService {
  private currentUserSubject = new BehaviorSubject<User>({} as User);
  public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());

  private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
  public isAuthenticated = this.isAuthenticatedSubject.asObservable();

  constructor (
    private apiService: ApiService,
    private http: HttpClient,
    private jwtService: JwtService
  ) {}

  // Verify JWT in localstorage with server & load user's info.
  // This runs once on application startup.
  populate() {
    // If JWT detected, attempt to get & store user's info
    if (this.jwtService.getToken()) {
      this.apiService.get('/user')
      .subscribe(
        data => this.setAuth(data.user),
        err => this.purgeAuth()
      );
    } else {
      // Remove any potential remnants of previous auth states
      this.purgeAuth();
    }
  }

  setAuth(user: User) {
    // Save JWT sent from server in localstorage
    this.jwtService.saveToken(user.token);
    // Set current user data into observable
    this.currentUserSubject.next(user);
    // Set isAuthenticated to true
    this.isAuthenticatedSubject.next(true);
  }

  purgeAuth() {
    // Remove JWT from localstorage
    this.jwtService.destroyToken();
    // Set current user to an empty object
    this.currentUserSubject.next({} as User);
    // Set auth status to false
    this.isAuthenticatedSubject.next(false);
  }

  attemptAuth(type, credentials): Observable<User> {
    const route = (type === 'login') ? '/login' : '';
    return this.apiService.post('/users' + route, {user: credentials})
      .pipe(map(
      data => {
        this.setAuth(data.user);
        return data;
      }
    ));
  }

  getCurrentUser(): User {
    return this.currentUserSubject.value;
  }

  // Update the user on the server (email, pass, etc)
  update(user): Observable<User> {
    return this.apiService
    .put('/user', { user })
    .pipe(map(data => {
      // Update the currentUser observable
      this.currentUserSubject.next(data.user);
      return data.user;
    }));
  }

}

README.md中的说明说:

[如果要将API URL更改为本地服务器,只需编辑src / environments / environment.ts并将api_url更改为本地服务器的网址(即localhost:3000 / api)

但是,当我这样做时(将api_url:中的environment.ts更改为'http://localhost:4200/api'),并尝试创建一个帐户,该页面没有反应,并且在检查时在控制台中收到此消息:

POSThttp://localhost:4200/api/users404(未找到)

如何更改此设置,以便可以使用localStorage创建和存储用户?

angular jwt local-storage angular8 angular-local-storage
1个回答
0
投票

我们有2个环境文件1. environment.ts(开发)http://localhost:8000,其中8000是本地服务器的端口

  1. environment.prod.ts(部署)http:// *。:8080 / AnalyticsServer-1.0,其中*替换为IP,而8080是服务器(tomcat)和AnalyticsServer-的端口1.0是已部署的war文件的名称
© www.soinside.com 2019 - 2024. All rights reserved.