Sending data from the frontend to the backend

Currently, I am developing a website with Java on the backend (hosted via Spring) and Javascript managing the frontend. Although I have successfully sent code from the backend to the frontend using a RestController, I am facing difficulties in sending data from the frontend to the backend. Specifically, my goal is to create a login form with backend validation.

Here is the HTML Form code:

<form ng-submit="login">
  <input type="text" ng-model="form.username" placeholder="username">
  <input type="password" ng-model="form.password" placeholder="password">
  <input type="submit" value="Login">
</form>

Below is the Javascript login code snippet:

function auth($scope, $http, AppSettings, $state) {
  'ngInject';
  $scope.form = {};

  $scope.login = () => {
    $http({
      method: 'POST',
      url: AppSettings.getApiUrl('/login'),
      data: {
        user: $scope.form.username,
        password: $scope.form.password,
      },
    }).then(response => {
      if (response) {
        console.log(response.data);
        localStorage.setItem('token', response.data.token);

        $state.go('main');
      }
    }).catch(error => {
      console.log(error);
    });
  };
}

Last but not least, here's the Java Login Handler implementation:

@RestController
public class LoginHandler  {

    private static final Logger log = LoggerFactory.getLogger(LoginHandler.class);


    @RequestMapping("/login")
    public void getLoginInfo(@RequestParam Map<String,String> requestParams) {
        RestTemplate restTemplate = new RestTemplate();
        User user = restTemplate.getForObject("http://localhost:3003/auth", User.class);
        log.info(user.toString());

    }

}

Answer №1

When utilizing AngularJS to send data to the back-end and specifying the parameters with the data key, the information is transmitted in a request body rather than as request parameters.

To handle this in the Spring MVC controller, it is preferable to use @RequestBody to map the values back to the Map<String, String>. Update the following line:

public void getLoginInfo(@RequestParam Map<String,String> requestParams) {

to this:

public void getLoginInfo(@RequestBody Map<String,String> requestParams) {

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

A guide on showcasing a value in an Input box using AngularJS

Recently, I started delving into AngularJS and I am determined to create a user info editing page where the old info is displayed in input fields. The goal is to allow users to easily see and update their information. I previously achieved this without usi ...

Ng-If Doesn't Work in the Current View

I'm having trouble updating the ng-if in my HTML code below: <div id="shyBoxII" ng-if="robot.robot" ng-class="background"> <div class="row"><i class="fa fa-user-plus"></i></div> <div class="row"><i clas ...

Creating a versatile JavaScript library that is compatible with various platforms such as browsers, NodeJS, and single page applications like React

My question is: Is it possible to convert a basic file into a versatile library that can be utilized with Browsers (via script tag), Node JS, and Single Page Applications using a single codebase? In the past, I have primarily used existing libraries witho ...

Data is being stored in a fresh record rather than being saved within an array

I'm currently working with the MEAN stack and using the Multer module for uploading images. While I am able to successfully retrieve images from Angular and post image paths to a Mongoose collection, I am encountering an issue. Instead of receiving ...

What are the reasons behind Selenium Web Driver's inability to locate certain cssSelectors?

I recently discovered a great web scraping tool at while working on a project. However, I encountered an issue when using Selenium Web Driver in Java as it was returning a different number of results compared to the selector gadget. This discrepancy seems ...

Guide on selecting and initializing functions in AngularJS upon page load

When using AngularJS, how can I ensure that the "All Categories" button is highlighted and initialized on page load or refresh? This could possibly be achieved by utilizing ng-init or ng-options. Controller $scope.selectCategory = function(newCategory) { ...

Transferring information via a function to a modal component in VueJS

Seeking advice on passing data to a modal. I'm attempting to pass data to a modal, where a function within a v-for loop gathers the video URL for later opening. The modal is placed outside the v-for loop to prevent all videos from playing the same o ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

Having trouble locating and clicking on a button using various object locators?

While attempting to run the following Selenium Web driver script, I am encountering an issue: org.openqa.selenium.ElementNotVisibleException: Element is not currently visible <span class="button-inner">Login</span> @Test public void ...

Searching for a string value within an ArrayList using a custom class

As a business administration student dabbling in Java for fun, I'm currently tackling exercise 101 in a MOOC course from a Finnish university. The task at hand is to create a library program with a search function for books based on title, publisher, ...

Resetting a form in React JS: A step-by-step guide

How can I clear the input values in a React JS form upon clicking Reset? class AddFriendForm extends Component { constructor(props) { super(props) this.state = { firstname: '', lastname: '', } } render() { c ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

Guide: "Adding markers to user-uploaded images - A step-by-step tutorial"

I'm struggling to create a website that allows users to upload images and use specific tools. However, I am facing an issue where the marker I want to add is appearing all over the webpage instead of just on the image itself. How can I confine it to o ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Collapse the hamburger menu upon clicking on a link in the mobile menu

Whenever I click on a menu item, the page loads but the menu remains open. This JSX code represents the Mobile Menu: const MobileMenu = () => { const navigation = [ { link: '/applications', text: 'Applications' }, { link ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

I'm curious about how to use nightwatch.js to target a dynamically generated element with a dynamic value

I'm facing an issue with identifying dynamically generated elements in a list box using JQuery or some other scripting language. My goal is to select a specific market value that is passed dynamically. The code I've currently implemented is as fo ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...