-1

I am developing a rest service which recovers data from a database, on the backend side everything works well (I tested in postman it recovers the desired data as you can see in this photo):

postman

but frontend level it does not work it gives me the following error:

error error 2

yet I put the crossorigin in my controller, but it still does not work :(

here is the code for my controller:

package com.app.habilitation.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.habilitation.entity.EmploiEntity;
import com.app.habilitation.service.EmploiService;

@RestController
@SpringBootApplication
@CrossOrigin(origins = "*")
@RequestMapping("/emploi")
public class EmploiController {

    private EmploiService emploiService;

    @Autowired
    public EmploiController(EmploiService theemploiService) {
        emploiService=theemploiService;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/getall")
    public List<EmploiEntity> getAll() {

        return emploiService.findAll();

    }
}

and this is my dao code :

package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiDao extends JpaRepository<EmploiEntity, Integer> {


}

and this is my entity code :

package com.app.habilitation.entity;

import java.sql.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_P_EMPLOI")
public class EmploiEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer id;


    @Column(name="CODE")
    private String code;


    @Column(name="NOM")
    private String nom;

    @Column(name="DATEEFFET")
    private Date dateeffet;

    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="STATUT")
    private String statut;

    /*@OneToMany(mappedBy = "emploi", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    private List<UserEntity> users; */

    public Integer getId() {
        return id;
    }

    /* public List<UserEntity> getUsers() {
        return users;
    }

    public void setUsers(List<UserEntity> users) {
        this.users = users;
    } */

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }



    public EmploiEntity(Integer id, String code, String nom, Date dateeffet, Date datefin, String statut
            ) {
        this.id = id;
        this.code = code;
        this.nom = nom;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.statut = statut;

    }

    public EmploiEntity() {
    }

    @Override
    public String toString() {
        return "EmploiEntity [id=" + id + ", code=" + code + ", nom=" + nom + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", statut=" + statut + "]";
    }




}

this is my emploiService code :

package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.EmploiEntity;


public interface EmploiService {


    public List<EmploiEntity> findAll();
}

and this is my emploiServiceImpl :

package com.app.habilitation.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.EmploiDao;
import com.app.habilitation.entity.EmploiEntity;

@Service
public class EmploiServiceImpl implements EmploiService {

    private EmploiDao emploiDao;

    public EmploiServiceImpl(EmploiDao theEmploiDao) {
        emploiDao=theEmploiDao;
    }


    @Override
    @Transactional
    public List<EmploiEntity> findAll() {

        return emploiDao.findAll();
    }

}

this is my component.html :

<div class="inscription">

    <!-- Default form register -->
    <form class="text-center border border-light p-5">

        <p class="h4 mb-4">Sign up</p>

        <div class="form-row mb-4">
            <div class="col">
                <!-- First name -->
                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
            </div>
            <div class="col">
                <!-- Last name -->
                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">
            </div>
        </div>

        <!-- E-mail -->
        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">


        <!-- Login -->
        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <!-- Password -->
        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">


        <!-- Confirmation mot de passe -->
        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">


        <!-- Entite -->

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <!-- Emploi -->


        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>


        </select>


        <!-- Sign up button -->
        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>


    </form>
    <!-- Default form register -->

</div>

(focus more on this code ):

<!-- Emploi -->


        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>


        </select>

this is my emploi class :

import { User } from './user';

export class Emploi {

    IDENTIFIANT: number;
    CODE: string;
    NOM: string;
    DATEEFFET: Date;
    DATEFIN: Date;
    STATUT: string;
    users: User;
}

and this is my .ts component :

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

@Component({
  selector: 'app-inscription',
  templateUrl: './inscription.component.html',
  styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");


  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }


  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}

and this is my service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

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

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }


  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }


  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}

(focus more on this code in service) :

public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

can someone help me please ??

R. Richards
  • 21,615
  • 9
  • 55
  • 58
  • on frontend level you need to send your username and password in headers like you sent in postman. – Aakash Garg May 31 '20 at 16:40
  • I don't think you're setting your headers properly. See this: https://angular.io/guide/http#adding-headers – R. Richards May 31 '20 at 16:42
  • https://stackoverflow.com/questions/53613529/angular-6-http-get-request-with-http-basic-authentication – Aakash Garg May 31 '20 at 16:48
  • Does this answer your question? [Angular 6 HTTP Get request with HTTP-Basic authentication](https://stackoverflow.com/questions/53613529/angular-6-http-get-request-with-http-basic-authentication) – R. Richards May 31 '20 at 16:49
  • Check network tab and see what header angular is sending. 401 means unauthorised, so it's likely it's just that a correct token is not sent – David May 31 '20 at 16:51
  • I checked in network the only error displayed is : Request URL: http://localhost:8484/emploi/getall Request Method: GET Status Code: 401 Remote Address: [::1]:8484 Referrer Policy: no-referrer-when-downgrade – Nawfal bougrine May 31 '20 at 17:00
  • there is spring security implemented in my application and I set as login: hr and password: hr (as login and password to authenticate in on application) I authenticate in postman with an auth basic to be able to display the result. in angular do i have to do a few things like this if i want to get the result? If yes, how ? (sorry if it's a stupid question but I'm just a beginner in angular) – Nawfal bougrine May 31 '20 at 17:04
  • I was advising you to check the request's headers in the network tab. And compare with what you send in postman. Maybe add the angular headers and postman headers to your question. – David May 31 '20 at 18:10

1 Answers1

1

Have you tried:

  public getEmploi(): Observable<Emploi[]> {
    return this.http.get<Emploi[]>(this.url_getAllEmploi, {responseType:'text'});
  }
gsa.interactive
  • 495
  • 1
  • 7