Search code examples
angulartypescriptfetch-api

How to send fetch api request with object parameter with Angular?


I try to send a user object in json format to backend and I get username, password, email etc. at backend from the parameter. Here is my backend code:

@PostMapping("/login")
    public User loginUser(@RequestBody User user) throws Exception {
        User userObj = null;
        if (!isNull(user.getEmail()) && !isNull(user.getPassword())) {
            userObj = userService.getUserByEmailAndPassword(user);
        }
        if (isNull(userObj)) {
            throw new Exception("Bad credentials");
        }
        return userObj;
    }

As you see I am not sending string parameters, I am sending the whole object.

In frontend, my component code is:

async loginUser(user:User) {
   let response = await this._service.LoginUser(user);
   let data = response.json();
   console.log(data);
 }

and this code is calling the following method from the service class,

LoginUser(user: User) {
    var url = new URL"http://localhost:8080/login");
    var params =[[user]];
    url.search = new URLSearchParams(user).toString;
    return fetch("http://localhost:8080/login", user)
  }

But there is something wrong about sending request with parameter user. How can I make this request?(without using Jquery)


Solution

  • fetch() by default, sends a GET request and you don't need to pass a second argument to fetch when making a GET request.

    If you want to pass user data in URL using query parameters, you will need to pass the URL with query string to fetch as the only argument

    LoginUser(user: User) {
        var url = new URL"http://localhost:8080/login");
        url.search = new URLSearchParams(user);
        return fetch(url.toString());
    }
    

    If you are trying to log user in, DON'T pass user authentication data in the URL. Instead make a POST request.

    In order to send a POST request, you need to pass a second argument to fetch() which is an object containing different properties representing various request options.

    fetch("http://localhost:8080/login", {
      method: 'POST',
      body: JSON.stringify(user)
    }
    

    For details on Fetch API, see MDN - Using Fetch