Search code examples
javaspringcorssame-origin-policy

Problem Cors: No 'Access-Control-Allow-Origin' header is present on the requested resource


I cannot resolve this error; I added @CrossOrigin(origins="http://localhost:4200") but the error still persists.

RestAPIController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


(origins = "http://localhost:4200") 
@RestController
@RequestMapping("/api/customer")
public class RestAPIController {
    
    @Autowired
    CustomerServices customerServices;
    
    @PostMapping("/create")
    public ResponseEntity<Message> addNewCustomer(@RequestBody Customer customer) {
        try {
            Customer returnedCustomer = customerServices.saveCustomer(customer);
            
            return new ResponseEntity<Message>(new Message("Upload Successfully!", 
                                            Arrays.asList(returnedCustomer), ""), HttpStatus.OK);
        }catch(Exception e) {
            return new ResponseEntity<Message>(new Message("Fail to post a new Customer!", 
                                            null, e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);           
        }
    }
    .
    .
    .
    .
    
}

what do you advise me to do? Thank you

I have tried in every way, I have found and tried several examples on this site but the problem still appears.


Solution

  • This is an old question.

    You should add this overide method in Config class which extend WebMvcConfigurer

            registry.addMapping("/**")
                    .allowCredentials(true)
                    .allowedHeaders("*")
                    .allowedMethods("*")
                    .allowedOrigins("http://localhost:3000")
                    .maxAge(3600);
       }