首页 > 解决方案 > 问题 Cors:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

我无法解决此错误;我添加了 @CrossOrigin(origins="http://localhost:4200") 但错误仍然存​​在。

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);           
        }
    }
    .
    .
    .
    .
    
}

你建议我怎么做?谢谢

我已经尝试了各种方式,我在这个站点上找到并尝试了几个示例,但问题仍然存在。

标签: javaspringcorssame-origin-policy

解决方案


这是一个老问题。

您应该在扩展的 Config 类中添加此覆盖方法WebMvcConfigurer

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

推荐阅读