响应中的Access-Control-Allow-Credentials标头为“”,必须为“ true”

时间:2018-09-03 06:54:48

标签: javascript java

我正在尝试向REST api发送评论。其余的API已经为我的应用程序地址设置了CORS。

后端

@RestController
@CrossOrigin(origins = "http://localhost:8000", allowedHeaders = "*", methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
@RequestMapping("/api")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;

    // Get All Comments From a certain workitemId
    @GetMapping("/comments/{workitemId}")
    public List<Comment> getTicketHistory(@PathVariable Long workitemId) {
        return commentRepository.getCommentsByWorkitemId(workitemId);
    }

    // Create a comment related with a given Workitem
    @PostMapping("/comment")
    public boolean createComment(@RequestBody Comment comment) {
        commentRepository.save(comment);
        return true;
    }
}

但是我明白了

  

无法加载http://localhost:8999/api/comment:响应   预检请求未通过访问控制检查:   响应中的“ Access-Control-Allow-Credentials”标头为“   当请求的凭据模式为“包含”时,必须为“ true”。   因此,不允许访问来源“ http://localhost:8000”。的   XMLHttpRequest发起的请求的凭据模式为   由withCredentials属性控制。

我的代码:

$http.post(baseUrl + "/comment", vm.comment).then(
      function(response) {
        // success callback
        console.log("Comment Submitted!");
      },
      function(response) {
        // failure call back
         console.log("Error while submitting the comment");
      });

2 个答案:

答案 0 :(得分:2)

您忘记添加:

allowCredentials=true

应该是:

@CrossOrigin(origins = "http://localhost:8000", allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})

答案 1 :(得分:2)

尝试将allowCredentials = "true"注释中的@CrossOrigin添加为

@CrossOrigin(
    allowCredentials = "true",
    origins = "http://localhost:8000", 
    allowedHeaders = "*", 
    methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT}
)

这可能有用。