Spring Boot receiving null values from Angular form submission

I am currently working on a form in Angular that is used to submit information such as author, context, and recently added images. However, I have run into an issue where I am able to successfully retrieve the author and context, but not the images (it always shows up as null).

=== Backend with SpringBoot === Model:

public class Content {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String context;
    private String author;
    private String images;

    public Long getId() { return id; }
    public String getContext() { return context; }
    public String getAuthor() { return author; }
    public String getImage() { return images; }
}

Controller:

@PostMapping("/create")
@ResponseBody
public Content saveContent(@ModelAttribute Content content){
    System.out.println(content.getImages());
    System.out.println(content.getAuthor());
    return null;
}

=== Frontend with Angular === home.component.ts:

submitForm() {
    const formData = new FormData();
    formData.append('author', 'John Smith');
    formData.append('images', 'sample.png');

    this.http.post<any>('/create', formData).subscribe({
        next: (data) => {
          console.log('Success');
        },
        error: (err) => {
          console.log(err);
        },
    })
}

=== Database with MySQL === Database columns

Answer №1

In Angular post requests, the second parameter refers to the body of the request. This means that in your Spring controller, you will need to use the RequestBody annotation instead of ModelAttribute.

Answer №2

If your client application is built with Angular, it's important that your backend provides rest APIs for the clients to consume.

To resolve this issue, you need to take the following steps:

1) Make sure to use a RestController instead of a simple controller in order to map the response correctly. Annotate your controller with @RestController

2) Update your code to bind a request body using the @RequestBody annotation

@RestController // Use this annotation
public class ContentController {
  @PostMapping("/create")
  public Content saveContent(@RequestBody Content content){
  // Include your persistence logic (e.g. saving in a database)
  return content;
  }
}

3) Define a class named Content with the fields expected by your backend

export class Content {
  author: string;
  images: string;
}

4) Update your Angular code to send a request body directly without using FormData

submitForm() {
   const contentRequest : Content = {
    author: 'John Smith',
    images: 'sample.png'
}

 this.http.post<any>('/create', contentRequest).subscribe({
        next: (data) => {
          console.log('Success');
        },
        error: (err) => {
          console.log(err);
        },
    })

}

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

The module 'AppModule' is importing an unexpected value 'AppAsideModule'. To resolve this issue, make sure to include an @NgModule annotation

Recently, I attempted to upgrade my Angular project from version 13 to version 17. However, during the process, I encountered an error stating "Unexpected value 'AppAsideModule' imported by the module 'AppModule'. Please add an @NgModul ...

Angular component showcasing the usage of a nested input-group

I have developed an input component and a datepicker component in Angular. The input component generates the appropriate input tag based on the type parameter, whether it's text, number, etc. Meanwhile, the date picker is another component that contai ...

The MUI theme seems to be missing its application

As a newcomer to MUI, I'm facing challenges when trying to apply a custom theme. My goal was to create a new variant for the button using the code snippet below: // @ts-nocheck import React, {FC} from 'react'; import { createTheme, ThemeProv ...

Using PHP to update MySQL on Android by sending data in JSON format

I attempted to create an activity that would update a MySQL database. Here is the code for the web server: <?php //error_reporting(0); require_once('db_config.php'); if($conn){ $sql = "UPDATE order_detail SET order_status ='co ...

Angular Service Worker - Resolving Font Awesome Cross-Origin Resource Sharing

After successfully running our Angular app in production for a year, we recently deployed support for PWA (Progressive Web App) functionality. Everything seemed to be working smoothly until we encountered an issue specific to some Samsung mobile devices. ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

Column not recognized in field list for Node.js

I have encountered a puzzling issue while working with the following code in nodejs. Despite using npm's mysql library and confirming that all columns are correct in my MySQL database, I keep receiving an error message stating: "Unknown column 's ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

Using Java for internet communication

Imagine a scenario similar to video game servers. You can launch an application that establishes a server on your computer, complete with an IP address and port number. For instance, how could you create an application where one host program creates a ser ...

Update the SQL table for the currently logged in user using PHP code

I am currently facing a challenge where I need to capture input from a text box for a logged-in user and insert it into the corresponding row in a database. Presently, I can successfully add data to the database but it creates a new record instead of updat ...

How can you customize the sorting order of posts in WordPress using custom fields and post types?

I am seeking a way to implement a select box on my website that will enable users to choose the order in which posts are displayed, similar to how it works on YouTube with options for date and relevance. Specifically, I am working on displaying a list of ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Tips for dynamically injecting HTML content in an Angular web application

I'm currently working on an angular website dedicated to a specific book. One of the features I want to include is the ability for users to select a chapter and view an excerpt from that chapter in HTML format. However, I'm facing a challenge wh ...

The call stack size has reached its maximum limit;

Encountering an issue with the use of componentDidMount(). This method is intended to display a Tooltip by utilizing the function _getContentTooltip(). However, the problem arises as it triggers the error message common.js:444 RangeError: Maximum call st ...

What is the best method for securely storing passwords in a database?

<?php if(isset($_POST['submit'])) { include ("connect/connect.php"); static function generatePassword($length = 8) { $chars = "1234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $i = 0; $password = ""; while ( ...

In Angular 2, I am having trouble reaching the properties of an object nested inside another object

I have a variable named contact. When I used console.log(contact) to display its contents, this is what I got: addresss:[] company:"" emails:[] id:3 internet_calls:[] lat:"10.115730000000001" lng:"76.461445" name:"Diji " phones:[] special_days:[] timesta ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Obtain the authorization token

To retrieve the token which contains abundant information, I'm utilizing the following method: getTokenSilently$(options?): Observable<string> { return this.auth0Client$.pipe( concatMap((client: Auth0Client) => from(client. ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...