我的API出现离子401错误未经授权 这是我的Service Allet:我的httpService:我的typescript文件:我的路线: Controller函数:

如何解决我的API出现离子401错误未经授权 这是我的Service Allet:我的httpService:我的typescript文件:我的路线: Controller函数:

我将我的API集成到离子视图中,因此我想将我的汇款端点从一个叶子端口集成到另一个叶子端口,但出现401错误。

这是我的源代码:


离子源转移代码:

  • 这是我的Service Allet

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import { StorageService } from './storage.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class WalletService {

  constructor(
    private httpService: HttpService,private storageService: StorageService,private router: Router
  ) { }

  transfert(data: any): Observable<any>{
    return this.httpService.post("ewallet/transfer",data);
  }
}
  • 我的httpService

import { environment } from './../../environments/environment.prod';
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from "@angular/common/http";
import { headersToString } from "selenium-webdriver/http";

@Injectable({
  providedIn: 'root'
})
export class HttpService {  
  httpOptions = {
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json'
    }),withCredintials: false
  };

  constructor(
    private http: HttpClient
  ) {}

  post(serviceName: string,data: any){
    const url = environment.apiUrl + serviceName;
    return this.http.post(url,data,this.httpOptions);
  }

  getById(serviceName: string,id: string){
    const url = environment.apiUrl + serviceName;
    return this.http.get(url+"/"+id);
  }

  getAll(serviceName: string){
    const url = environment.apiUrl + serviceName;
    return this.http.get(url);
  }

  update(serviceName: string,id: string,data: any){
    const url = environment.apiUrl + serviceName;
    return this.http.put(url+"/"+id,this.httpOptions);
  }

  modify(serviceName: string,data: any){
    const url = environment.apiUrl + serviceName + id;
    return this.http.patch(url,this.httpOptions);
  }

  delete(serviceName: string,id: string){
    const url = environment.apiUrl + serviceName;
    return this.http.delete(url+"/"+id,this.httpOptions);
  }
}
  • 我的typescript文件:

import { ContactService } from './../services/contact.service';
import { AuthConstants } from 'src/app/config/auth-constant';
import { StorageService } from 'src/app/services/storage.service';
import { SuccessmodalPage } from './../modals/successmodal/successmodal.page';
import { Component,OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { WalletService } from '../services/wallet.service';

@Component({
  selector: 'app-requestreview',templateUrl: './requestreview.page.html',styleUrls: ['./requestreview.page.scss'],})
export class RequestreviewPage implements OnInit {
  public typee: any;
  public title: any;
  public amount: string;
  public contact: any;
  public authUser: any;
  public data: any = {
    name: '',email: ''
  };

  public dataTransfert = {
    amount: '',destinationAccountNumber: ''
  }

  constructor(
    public modalCtrl: ModalController,private route: ActivatedRoute,private authService: AuthService,private walletService: WalletService,private contactService: ContactService
  ) { }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.typee = params["type"];
    });

    //get auth user informations
    this.authService.userData$.subscribe((res: any) =>{
      this.authUser = res;
      console.log(res.customer.accountNumber);
    });

    //get contact datas
    this.contactService.contactData$
      .subscribe(data => (this.contact = data));

    //get amount data
    this.contactService.amountData$
      .subscribe(data => (this.amount = data));
    //set title
    this.setTitle();

    console.log('données a transferer: ',this.getData());
  }

  getData(){
    this.dataTransfert.amount = this.amount;
    this.dataTransfert.destinationAccountNumber = this.contact.accountNumber;

    return this.dataTransfert;
  }

  transfert(){
    this.walletService.transfert(this.getData()).subscribe((res: any) =>{
      this.showModal();
    });
    
  }

  setTitle() {
    if (this.typee == 'request') {
      this.title = "Review and Request";
    }

    if (this.typee == 'send') {
      this.title = "Review and Send";
    }
  }

  async showModal() {
    const modal = await this.modalCtrl.create({
      component: SuccessmodalPage,backdropDismiss: true
    });

    return await modal.present();
  }
}

(在服务器上)我的node.js代码:

  • 我的路线:

router
  .route('/transfer')
  /**
   * @api {post} v1/ewallet/transfer eWallet Transfer
   * @apiDescription Make a transfer to another eWallet
   * @apiVersion 1.0.0
   * @apiName Transfer
   * @apiGroup eWallet
   * @apiPermission customer
   *
   * @apiHeader {String} Authorization Customer's access token
   *
   * @apiParam  {Number{0...50000}}       amount       Decimal whith two fraction digits.
   * @apiParam  {Number}             destinationAccountNumber  Transaction's destinationAccountNumber
   *
   * @apiSuccess {Object}  transaction       Transaction.
   * @apiSuccess  {String}  transaction.id     Transaction's id
   * @apiSuccess  {Number}  transaction.accountNumber   Transaction's accountNumber
   * @apiSuccess  {Number}  transaction.destinationAccountNumber   Transaction's destinationAccountNumber
   * @apiSuccess  {String}  transaction.operation  Transaction's type of operation (deposit,withdrawal,transfer,fee)
   * @apiSuccess  {Number}  transaction.amount     Transaction's amount
   * @apiSuccess  {Number}  transaction.reference     Transaction's reference
   * @apiSuccess  {Date}    transaction.createdAt      Timestamp
   *
   * @apiSuccess {Object}  customer       Customer.
   * @apiSuccess  {String}  customer.id             Customer's id
   * @apiSuccess  {Number}  customer.accountNumber  Customer's accountNumber
   * @apiSuccess  {String}  customer.name           Customer's name
   * @apiSuccess  {String}  customer.email          Customer's email
   * @apiSuccess  {String}  customer.role           Customer's role
   * @apiSuccess  {Date}    customer.createdAt      Timestamp
   *
   * @apiError (Bad Request 400)   ValidationError  Some parameters may contain invalid values
   * @apiError (Unauthorized 401)  Unauthorized     Only authenticated customers can create the data
   * @apiError (Forbidden 403)     Forbidden        Only admins can create the data
   */
  .post(authorize(),validate(walletTransfer),controllerWallet.transfer); //authorize(),walletTransfer,
  • Controller函数:

/**
 * eWallet Transfer
 * @public
 */
exports.transfer = async (req,res,next) => {
  try {    
    const transferResponse = await transferService.transfer(req.customer.accountNumber,req.body.amount,req.body.destinationAccountNumber);    
    res.json(transferResponse);    
    
  } catch (error) {
    next(error);
  }
};

感谢您的帮助,谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-