Exploring APIs during full-stack development

When it comes to fetching APIs created on the backend, I encounter some challenges. While handling everything correctly on the front-end server side, issues arise with error handling as the catch(error) method only captures errors originating from the front-end rather than the back-end. My tech stack mainly revolves around VueJS and Spring Boot. Let me provide an example to better illustrate my situation.

  JwtUtils jwtUtils;
  @PostMapping("/signin")
  public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    
    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();    
    List<String> roles = userDetails.getAuthorities().stream()
        .map(item -> item.getAuthority())
        .collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt, 
                         userDetails.getId(), 
                         userDetails.getEmail(), 
                         roles));
  }

On the front-end side, I simply consume this API by creating a service in VueJS that is invoked upon a button click within one of my views. Here's how my service looks:

class AuthService{

    login(user){
        return  fetch("http://localhost:100/api/v1/auth/signin",
      {method : "POST",
      headers:{
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        email:user.email,
        password: user.password,
      }),
        
      }).then( response => response.json()).then(data =>{
          if (data.accessToken){
              localStorage.setItem('user',JSON.stringify(data))
          }
          return data})
      
    }
    logout(){
        localStorage.removeItem('user')
    }
}
export default new AuthService();

This service is connected to my module (Vuex) in the localstore:

import AuthService from '../services/auth.service';
const user = JSON.parse(localStorage.getItem('user'));
const initialState = user
  ? { status: { loggedIn: true }, user }
  : { status: { loggedIn: false }, user: null };
export const auth = {
  namespaced: true,
  state: initialState,
  actions: {
    // relevant action methods here
  },
  mutations: {
    // relevant mutation methods here
  }
};

Lastly, there is a view responsible for triggering the actions - it comprises a form with input fields that are sent to the backend via a post method call. The LoginForm.vue file has the following content:

<template>
  <div id="nav">
    <!-- components -->
  </div>
</template>
<script>
//script content
</script>

In conclusion, while I am able to handle errors effectively, I am unsure if my approach aligns with conventional practices. For instance, should I rely on if statements to manage errors from the backend or explore alternative methodologies? Any insights on securing my system would be greatly appreciated.

Form Screenshot

Answer №1

When it comes to error handling, it's typically more efficient for the backend to manage error messages. Whether they are generic or specific, the frontend can simply display the error message provided by the backend. By following this method, you won't have to struggle on the frontend trying to decipher various error codes like

if res.status == 403 || res.status === 404
. The main focus will be on accessing and displaying the error.message property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with the loading of intricate attribute data into an array of arrays

I am struggling with loading different data attributes into an array of arrays. I have managed to load single data attributes into the dataArray, but when it comes to the data-size which contains groups of arrays in string format, I am facing difficulties ...

Using getElementsByTagName in E4X code involves querying for specific

Is it possible to retrieve an array of elements in E4X for an unknown tagname, similar to how the DOMs getElementsByTagName function works, within a function? My initial idea was: (function (doc, tag) { return doc..[tag]; }) Can this be achieved? ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

"Learn the steps to dynamically update the ng-bind value of a single element within an ng-repeat loop by

I'm new to Angular and I'm working on developing a shopping cart. I'm currently facing an issue with adding the 'Added!' value when clicking on the "add to cart" button. Here is my code <div ng-repeat="item in products"> < ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Issue with Bootstrap List Group Nested Links causing them to stop functioning after initial selection

I am trying to implement page navigation using the Bootstrap List-group class in HTML. However, I am facing an issue where the nested links 'Link 1' and 'Link 2' freeze after the first click. The desired functionality is as follows: ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Using JavaScript, capture and rearrange the colors of the store's section. JS

I'm facing a challenge with creating dynamically colored divs based on different sections in the background. While I can achieve this using CSS, I wonder if there's a more efficient way to handle the colors with JavaScript. In my current setup, ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Encountering issues with Windows 8 PhoneGap FileTransfer when trying to transfer text files

I'm facing an issue while attempting to upload a file to a server - the process seems successful, but the file doesn't actually transfer. I've temporarily hard-coded some values, but here's the code snippet: var options = new FileUplo ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Determine if localStorage is set using jQuery

There is a text on the page inside a div with the id clicker. When this div is clicked, the localStorage value should toggle between 1 and 0. I have provided an example in this JSFiddle link. Although it seems to be working by toggling the value, there ar ...

flylatex is struggling to locate some modules

When I try to run flylatex from github on Debian and Ubuntu, I encounter the following Error. I'm not sure if there's an issue with my nodejs setup or if flylatex itself has an error. To troubleshoot, I initially ran npm install -d in the working ...

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

What is the best way to transfer an object property to an event handler function for executing DOM manipulation tasks?

I am working on a React-rendered HTML page that displays a list of objects representing websites. I have successfully stored these objects in memory and can show them in a long list on the page without any issues. Recently, I added a button for each objec ...

Pattern-matching system for identifying specific words or phrases in a given string in order to facilitate replacement operations

I need help with a coding challenge involving sentences and arrays. The task is to replace specific words or phrases in a sentence with HTML tags for user interaction. Here's an example using JavaScript: var sentence = "Yes. I know him from my neig ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...