What is the most efficient way to post data to the most recently added resource/record in a database?

I need to update specific data in an existing record within the database using a POST method. Currently, every time I make a POST request, it creates a new record instead of updating the existing one. What is the most straightforward approach to achieve this?

My frontend is built with Angular and I am using Glassfish RESTful server as my backend.

Here is the TypeScript file:

[typescript code here]

I am attempting to post data to the latest/newest added record at the following link:

'http://localhost:8080/aquadine-jee/resources/restaurant'

Backend code snippet:

[Java code snippets here]

Answer №1

One issue you may be encountering is that by using an HTTP POST request to update a record, a new record is being created instead of updating an existing one. It appears that the URL is the same for both creating and updating records, causing this confusion. To differentiate between creation and update operations, consider utilizing the HTTP PUT method instead. Here's how you can modify your code:

this.http.put('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
  .subscribe(res => {
      console.log('response' + ' ' + res); // log results or log error
    },
    err => {
      console.log('Error occurred');
    });
  • You may find it beneficial to move your API calls to a Service Class.
  • Consider learning more about Rest API practices.

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

Tips for integrating a REST facade into your application

I am in search of a solution to develop a front-facing interface that can divert requests to different web services. Aside from forwarding requests, the interface should also handle user authentication and authorization. Any suggestions on how to effecti ...

Managing the lifecycles of extended class instances in Angular 2 - what's the best approach?

The code snippet below is causing an issue for me in Angular 2.4.9: export class MyComponent extends BaseComponent implements OnInit { type = 2; constructor() { super(); } ngOnInit(){ console.log('inited type', this.type) } } ...

What is the method of including a null option in a dropdown menu?

I have a basic dropdown menu with the placeholder text "none." I want users to be able to clear their selection without adding another option to the dropdown. Can anyone help me achieve this? Thank you! Below is my code snippet: Check out the live demo h ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

AngularJS encountered an unexpected HTTP status with code -1

In my efforts to implement offline functionality in an AngularJS app with Cordova for Android and iOS, I created an HTTP interceptor that checks the status of HTTP requests and determines the appropriate action. A few months ago, I had a working version o ...

NG-Bootstrap Navigation Bar- dynamic hamburger icon animation

I have been trying to implement an animated hamburger animation on the navbar using ng-bootstrap and Angular, but so far I have had no success. While the Navbar does collapse as expected, it lacks the animation and transformation into an 'x'. I w ...

Ways to protect your ExpressJS RESTful API from unauthorized access

Is it possible to enhance security for an expressjs RESTful API so that only a react native app and react website have access? For example, the server runs on port 8000, the react native app is on port 3000, and the website on port 5000. It’s desired th ...

Troubleshooting conflicting dependencies in Angular 17

After setting up a new project with Angular 17, I encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Template reference does not connect to the ApexChart graphic

As a newcomer to ApexCharts.js, I am currently working on setting up a Vue3 app using Composition API along with the setup syntax. My goal is to reference the template ref of 'apexchart' so that I can later call the dataURI() function on it. I am ...

Tips for adjusting the angle in SVG shapes

I have designed an svg shape, but I'm struggling to get the slope to start from the middle. Can someone please provide assistance? <svg xmlns="http://www.w3.org/2000/svg" fill="none"> <g filter="url(#filter0_b_1_2556)"&g ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

The mandatory input field property is malfunctioning, and the color of the input field remains unchanged

<div class="container"> <h1>Register Form</h1> <form> <div class="form-group" > <label for="name">Full Name</label> <input type="text" class="form-control" [ngClass]="{& ...

What is the best approach to sending numerous queries from a single endpoint using Express?

I am attempting to perform multiple database queries and create an object that stores each response from the database in a specific field. Below is the code I have written: router.post('/search', (req, res) => { var collection = db.get(). ...

Encountering CORS issue, despite having the CORS annotation in the Spring Boot application

Here is my Spring Boot code: @GetMapping("/currentUser") public Map<String, String> testController(Authentication authentication){ User user=(User)authentication.getPrincipal(); HashMap<String, String> map = new HashMap<>(); m ...

The solution to accessing a global variable within the onerror event of an audio object

My goal is to retrieve the value of the isDisabled variable from within the audio.onerror function and then reset it, but I am encountering difficulty in achieving this. public isDisabled: boolean = false; private verifyPrompt(url: string): boolean{ ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

Is it possible to extract TypeScript types from one interface in order to integrate them into another separate interface?

Having a TypeScript interface defined as follows: interface SampleShape { prop1?: string; prop2?: string; } Additionally, I have another separate interface in mind to utilize: interface Payload { model: { name?: string; prop1?: ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Is VSCode disregarding tsconfig.json and compiling individual files, causing misleading error messages to appear?

After updating typescript, angular, and all the libraries in my project, I encountered a new issue that was not present before. Although I successfully ensured that my code builds without any errors or warnings from the command line, Visual Studio Code sta ...

The 'async' keyword is not permitted in this context within a TypeScript React application

An issue has arisen with the aync, indicating that the async modifier is not permitted in this context: private async getValue= (acc: Access): void => { await this.service.getForm(''); } It appears that there might be an ...