-1

I try to make a POST request to my springboot app hosted on heroku,

const email = 'x@x.com';
const password = 'x';

const data = JSON.stringify({
    email,
    password
});

fetch(
    'https://culinareat-test.herokuapp.com/api/user/users/_login', 
    {
        method: 'POST',
        headers : {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        },
        body : data,
    }
).then(res => {
    console.log(res);
})

I got this as the response:
Response

This is the controller on my springboot app:

@RestController
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    @RequestMapping(method = RequestMethod.POST, value = "/user/users/_login")
    public LoginResponse logUserIn(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request){
        return userService.logUserIn(loginRequest, response, request);
    }

    //another endpoints
}

I tried to do this from another articles i just read on stackoverflow:

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
    }
}

Still, it does nothing and i still cannot do the request. Any recommendation what should i do? Is there anything i should add on the server-side? Thanks in advance!

2 Answers2

0

You need to add annotation @CrossOrigin in your controller

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    @RequestMapping(method = RequestMethod.POST, value = "/user/users/_login")
    public LoginResponse logUserIn(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request){
        return userService.logUserIn(loginRequest, response, request);
    }

    //another endpoints
}
-1

Keep in mind that cross-origin issues are raised by Browsers. By default, if you are running javascript on origin http://localhost, you cannot specify CORS for localhost on the back-end.

Browsers such as Chrome do not allow javascript running on origin http://localhost to share resources in a cross-origin manner. See answer https://stackoverflow.com/a/10892392/15262845.

The solution is simple. Resolve a domain, e.g., example.com to 127.0.0.1 in hosts file. Then request example.com:8080 or example.com to load your front-end application and post the request from example.com origin.


Besides, you can always debug CORS by navigating to Network tab and copy, paste these two following headers.

access-control-allow-credentials: true
access-control-allow-origin: http://example.com/
justthink
  • 439
  • 3
  • 6