【问题标题】:Angular, error 500 after sending the request in the headerAngular,在标头中发送请求后出现错误 500
【发布时间】:2021-06-15 08:36:08
【问题描述】:

我很难将正确的角度请求传递给标题。这是我的服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } 
from '@angular/common/http';
import { Utente } from '../model/Utente ';
import { Prodotto } from '../model/Prodotto ';
import { OktaAuthService } from '@okta/okta-angular';
import { Observable, from } from 'rxjs';
import { Carrello } from '../model/Carrello ';
import { userInfo } from 'node:os';
import { getLocaleCurrencyCode } from '@angular/common';


const headers = new HttpHeaders().set('Accept', 'application/json');

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

 constructor(
private httpClient:HttpClient, private oktaAuth:OktaAuthService     ) {}

  getCarr(){
return this.httpClient.get<Carrello[]>('http://localhost:8080/prodotti/utente/vedicarrelloo', {headers} );
}
}

这是我的弹簧方法:

@Transactional(readOnly = true)
public List<Carrello> getCarrello(@AuthenticationPrincipal OidcUser utente){
    Utente u= utenteRepository.findByEmail(utente.getEmail());
    return carrelloRepository.findByUtente(u);
}

在控制台中我收到此错误(错误 500):

https://i.stack.imgur.com/BiONS.png

此错误在我的控制台中对应于“java.lang.NullPointerException: null.

但是如果我访问 localhost:8080,我可以正确看到答案,所以我假设在 Angular 中传递请求标头时存在问题,谁能告诉我我哪里错了,好吗?我指定仅在存在 OidcUser 的方法中出现此错误,其余的工作正常。谢谢!

【问题讨论】:

    标签: okta primavera


    【解决方案1】:

    您需要在请求中发送访问令牌。赞this

    import { Component, OnInit } from '@angular/core';
    import { OktaAuthService } from '@okta/okta-angular';
    import { HttpClient } from '@angular/common/http';
    
    import sampleConfig from '../app.config';
    
    interface Message {
      date: string;
      text: string;
    }
    
    @Component({
      selector: 'app-messages',
      templateUrl: './messages.component.html',
      styleUrls: ['./messages.component.css']
    })
    export class MessagesComponent implements OnInit {
      failed: Boolean;
      messages: Array<Message> [];
    
      constructor(public oktaAuth: OktaAuthService, private http: HttpClient) {
        this.messages = [];
      }
    
      async ngOnInit() {
        const accessToken = await this.oktaAuth.getAccessToken();
        this.http.get(sampleConfig.resourceServer.messagesUrl, {
          headers: {
            Authorization: 'Bearer ' + accessToken,
          }
        }).subscribe((data: any) => {
          let index = 1;
          const messages = data.messages.map((message) => {
            const date = new Date(message.date);
            const day = date.toLocaleDateString();
            const time = date.toLocaleTimeString();
            return {
              date: `${day} ${time}`,
              text: message.text,
              index: index++
            };
          });
          [].push.apply(this.messages, messages);
        }, (err) => {
          console.error(err);
          this.failed = true;
        });
      }
    }
    

    在 Spring 方面,如果您希望它接受 JWT,则需要更改为使用 Jwt 而不是 OidcUserExample here.

    @GetMapping("/")
    public String index(@AuthenticationPrincipal Jwt jwt) {
        return String.format("Hello, %s!", jwt.getSubject());
    }
    

    【讨论】:

    • 非常感谢您的回复。我不清楚,是否必须将该代码插入服务中,还是我需要创建一个新组件?在后一种情况下,我应该如何在服务中将请求发送到我的方法?谢谢
    • 另外,我指定在我的应用程序中,我有一个 auth.interceptor
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多