有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

POST请求时发生java Spring“No”AccessControlAllowOrigin“header”错误

我为客户机制作了一个带有spring服务器和angular的应用程序。 我正在尝试发出post请求,但出现以下错误:

Failed to load http://localhost:8080/statuts:

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 415."

我遵循了Spring教程:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-controller但没有任何东西适合我

至于我的spring代码,我已经放置了适用于所有其他请求(如get和put)的跨原点注释(如果我删除这一行,其他请求将发送完全相同的错误)

@CrossOrigin(origins = "http://localhost:4200")
public class ExempleController {

    @PostMapping(path="", consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Exemple addExemple(HttpServletRequest request) throws IOException {
        Exemple exemple = new Exemple();
        Exemple updatedStatut = objectMapper.readerForUpdating(exemple).readValue(request.getReader());
        statutRepository.save(updatedExemple);
        return exemple;
    }

我也尝试过全局配置,但同样的问题

我的请求是:

create(exemple: Exemple){
    return this.http.post("localhost:8080/exemples", JSON.stringify(exemple));
}

谢谢你的帮助

==编辑==

我没有提到它,但我的请求工作正常,因为它与PostMan配合得很好。这是客户端和服务器之间的通信问题


共 (2) 个答案

  1. # 1 楼答案

    我发现问题的答案是angular没有在post请求中发送所需的标题

    所以我把角度代码改成:

    create(exemple: Exemple){
        const headers1 = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
        return this.http.post(this.ExempleAPI, JSON.stringify(exemple), {headers: headers1});
    }
    

    希望它能帮助别人

  2. # 2 楼答案

    我不认为这里需要@CrossOrigin注释,除非您没有提到具体的原因

    关于使用Spring创建POST WebService,您可以遵循以下示例:

        @RestController
        public class ExempleController {
    
        @RequestMapping(value = "/", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
    
       public  @ResponseBody Exemple addExemple(@RequestBody LinkedHashMap map, HttpServletRequest request) throws IOException {
    
              // CODE HERE
            }
    
        }
    

    *您可以考虑用DTO类替换LinkedHashMap,但这会起作用。

    我希望有帮助;-)