【问题标题】:post request returns No 'Access-Control-Allow-Origin' header is present but actually header is set on server发布请求返回不存在“Access-Control-Allow-Origin”标头,但实际上标头已在服务器上设置
【发布时间】:2015-06-03 08:01:01
【问题描述】:

我向 java 后端发送一个 angularjs $http post 请求:

var url = 'http://192.168.88.245:9000/dologin';
$http.post(url, 
            {
                "email" : "admin@admin.com",
                "password" : "1"
            }, 
            {
                withCredentials: true
            }
        )

作为回应,我收到此错误:

OPTIONS http://192.168.88.245:9000/dologin 
(index):1 XMLHttpRequest cannot load http://192.168.88.245:9000/dologin. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

但是当我使用 chrome 的 Advanced Rest Client 扩展名并用它发送相同的请求时,服务器发送 200 OK。这是其余扩展响应中的标头:

Response headers 
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Credentials: true
Content-Type: application/json; charset=utf-8 
Access-Control-Max-Age: 300
Content-Length: 1181 

这两种情况有什么区别?

【问题讨论】:

  • 请求只能发送到同一主机,我认为您正在localhost 上运行脚本并将请求发送到192.168.88.245:9000
  • @madforstrength 是的,我在本地主机上。但是为什么扩展程序可以发送该请求而 $http 不能呢?
  • 这个问题的答案可能会有所帮助:stackoverflow.com/questions/10636611/…
  • @madforstrength 不正确,启用 CORS 允许您访问 x 域,并且在没有启用 CORS 的情况下,即使将请求发送到同一域但不同的端口被视为 x 域,即从 localhost:80 发布到localhost:81 Morteza 我认为你可能错误配置了后端,你使用的是什么 java?
  • 最后一个问题:对于高级休息客户端,您同时完成了这两个请求吗?我的意思是OPTIONS 和POST?

标签: angularjs


【解决方案1】:

angularjs(也可能还有其他框架)在POST 之前发出OPTIONS 请求,因此在OPTIONS 响应中他们会收到可以完成的方法列表

Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE

如果POST 在列表中,那么它将执行请求,在Advanced Rest Client 中,您可以选择发送OPTIONS 请求,执行与POST 相同的请求并查看输出,我猜是OPTIONS 没有在您的服务器端正确配置,当您使用Advanced Rest Client 进行POST 请求时,它会省略OPTIONS 角度失败的步骤

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 2021-02-18
    • 1970-01-01
    • 2019-03-08
    • 2013-11-29
    • 2014-07-28
    • 2014-01-19
    相关资源
    最近更新 更多