Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code:

 res= this.CS.postcompetenze(this.comp)

This is the servlet code:

postcompetenze(raw: any):boolean{
    var comp = '{'  +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"descrizione"'+':'+'"'+raw[1]+'" }'
    const obj = JSON.parse(comp);
    var res=this.http.post<any>('http://localhost:8080/postcompetenza', obj).subscribe(
        (val) => {console.log("POST call successful value returned in body", val);
})
if(res!= null)
return true
else
return false
}

And here is my endpoint in the backend:

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // adds a competence
public competenza addCompetence(@RequestBody competenza comp) {
    return cs.addCompetence(comp);
}

I would like to receive the status code response (200,300,400, etc.) along with or instead of the returned object.

Edit:

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // adds a competence
public ResponseEntity<?> addCompetence(@RequestBody competenza comp) {
    try {
        competenza response = cs.addCompetence(comp);
        return ResponseEntity.status(HttpStatus.OK).body(200);
    } catch (IllegalArgumentException e) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(409);

    } catch (BadRequest e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(400);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(500);
    }
}

This is how my backend looks now and my front-end:

   postcompetenze(raw: any){
    var comp = '{'  +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"description"'+':'+'"'+raw[1]+'" }'
    const obj = JSON.parse(comp);
    var res=this.http.post<any>('http://localhost:8080/postcompetence', obj).subscribe(
        (val) => {console.log("successful insertion "+JSON.stringify(val))
        if(val == "200")
            this.toastr.success("employee inserted correctly","SUCCESS");
        else
            this.toastr.error("employee not inserted","ERROR")
        },
        (error) => {                              
        console.error('error caught in component '+error)
        this.toastr.error("employee not inserted","ERROR")
        }
)

I'm working on this because I need to display a toastr for success or error. With this code, I can only get the success toast, but I'm having trouble displaying the error toast. Any help would be appreciated. Thank you.

Answer №1

If you want to retrieve the HttpStatus from the BackEnd response, ensure to include {observe: "response"} in the request parameters instead of the body.

Next, utilize a pipe along with a map function. Within the map function, extract the Http status and return your desired object for subscription. (I hope this explanation is clear)

this.http.get("https://jsonplaceholder.typicode.com/posts/1", {observe: "response"}).pipe(map(value => {
      //Here you can analyze the status or any other request details required (headers, response code, response body, etc.)
      console.log(value.status);
      return value.body; //returning just the body or any other information needed for subscription.
    })).subscribe(data => {
      //Here you have access to the body content.
      console.log(data);
    });

Additional tip:

For best practices, refer to the Java Naming Convention

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

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Monitor and compile numerous directories simultaneously in TypeScript (monorepo)

I've been searching far and wide online for a solution to my problem, but unfortunately, I haven't come across anything useful yet. Essentially, I am in need of a tool or method that will allow me to kick off TypeScript file Watching/Compiling in ...

Avoid page refreshing when modifying app.js in React

Today is only my second day using React and I started by creating a React app with "npx create-react-app." However, when I tried to make changes to the app.js file, they didn't appear on the page even after refreshing the browser multiple times. (My n ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

An issue occurred: Unable to access the 'login' property because of a TypeError

Setting up a login page and declaring an object in my login.ts file. public User: { login:"", senha:"", }; Utilizing [ngModel] to save values within the parameters of the object. <ion-item> <ion-label floating>Enter ...

What is the process for accessing a local .json file from a remote machine or folder?

I am currently working on a project that involves a .json file stored in my local folder. Along with the file, I have Javascript code in the same directory to access and read the values from the .json file. To open the file, this is the line of code I use: ...

Create a fresh trail underneath the overlay image

When utilizing fabric.js to draw a new path with isDrawingMode: true enabled (seen on the right side of the screenshot), I am encountering an issue where the path appears above my overlay image, which is a transparent png. https://i.stack.imgur.com/R3fGn. ...

How can I create a timed slideshow of images?

Is there a way to make a series of images slide automatically after closing or stopping a video? To see the specific website in question, click here: Upon visiting the site, a video pops up. How can I program the image slides to transition every 7 secon ...

The "src" attribute is missing from the image on the left side

I'm currently facing an issue with the src attribute in this code: An event updates the src based on a variable retrieved from a form. The image files cannot be renamed, so I must work with their existing names. The problem arises as all file names c ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Issues with pop-up windows on YII2 gridview

I am currently developing a web application using the Yii2 framework for my company to efficiently manage their storage. I have incorporated various plugins from kartik-v to enhance the functionality of the application. However, I am facing an issue with i ...

The reliability of next router events can sometimes be called into question as they do not always function consistently

I've been working on creating a loading screen for my Next.js project. The issue I'm facing is that sometimes the loading message stays on the screen and doesn't go away even after the page has loaded. I suspect this may be due to the state ...

Performing a deep insert in SAPUI5 with the Kapsel Offline App on an OData V2 Model

Query: What is the process for performing a "Deep Insert" from a SAPUI5 Client application on an OData V2 Model? Situation: In my SAPUI5 Client application, I need to Deep Insert an "Operation" along with some "Components" into my OData V2 Model. // h ...

Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes. data() { return{ selected:{ index: 2 } } } <style> .parent-table >>> .table-row:nth-child(/* here I intend to use ...

Utilizing JavaScript to manage sections within a dropdown menu

When dealing with this particular HTML code, there is a feature where a list item includes options such as all, a, b, c, and d. If the user selects 'All', it should restrict them from choosing any other items. However, if they do not choose &apos ...

Transfer the script from package.json to an npm package

In each of our plugins' root directories, there is a file named tools.js. This file contains a build function that assists in creating builds for the plugin. The package.json file references it like this: "scripts": { "build:node&qu ...