Issue
I am using Spring boot and angular. I have used the cross origin annotation mentioning my localhost port of angular but despite that I am getting the following error
src="https://i.stack.imgur.com/4uDuv.png" alt="enter image description here" />
My Spring boot codes are following
My Model class
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String password;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private boolean enabled = true;
private String profile;}
The controller class is following
package com.exam.portal.controller;
import com.exam.portal.entity.Role;
import com.exam.portal.entity.User;
import com.exam.portal.entity.UserRole;
import com.exam.portal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.Set;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/")
public User createUser(@RequestBody User user) throws Exception {
Set<UserRole>roles = new HashSet<>();
Role role = new Role();
role.setRoleId(44L);
role.setRoleName("NORMAL");
UserRole userRole = new UserRole();
userRole.setUser(user);
userRole.setRole(role);
roles.add(userRole);
return userService.createUser(user,roles);
}
@GetMapping("/{username}")
public User getUser(@PathVariable("username")String userName){
return userService.getUserByUserName(userName);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id")Long id){
userService.deleteUser(id);
}
}
Angular code of sevice
constructor(private http : HttpClient) { }
public addUser(user:any){
console.log("user data is ",user);
return this.http.post(`${baseURL}/user/`,user);
}
Solution
It looks like your variable baseURL
is missing the http:// before localhost:8088.
Answered By - Ruina
Answer Checked By - Robin (JavaFixing Admin)