【问题标题】:Angular JS - can't receive any response using $http.postAngular JS - 无法使用 $http.post 接收任何响应
【发布时间】:2013-11-07 14:55:29
【问题描述】:

我正在尝试使用 Angular JS 从 Web 服务获取响应,我可以使用简单的 curl 命令通过我的 shell 完美地访问它:

curl --header "Content-type: application/json" --request POST 
     --data '{"username": "name", "password": "pwd"}' 192.168.2.1:9000/ws/login


但是,当我尝试使用带有 $http.post 的 Angular 来访问它时,我会遇到一些“有趣”的行为。

虽然我的数据是:

    var url = "192.168.2.1:9000/ws/login"
    var postData = {
        username: un,
        password: pwd
    }


我已经尝试将 postData 作为 JSON 对象和字符串化 JSON

使用这样的调用:

    $http.post( url, postData ).
        success(function(data) {
        console.log(data)
        }).
        error(function(data, status, headers, config) {
            console.log(data, status, headers, config)
        })

甚至

    $http({
        url: url,
        method: 'POST',
        data: JSON.stringify(postData),
        headers: {'Content-type': 'application/json'}
        }).
        success(function(data, status, headers, config) {
            console.log('Success: ', data, status, headers, config)

        }).
        error(function(data, status, headers, config) {
            console.log('Error: ', data, status, headers, config)

        })

什么都不做。
什么都没有!


http:// 附加到 url,给我:
OPTIONS http://192.168.2.1:9000/ws/login 404 (Not Found) angular.js:7073
OPTIONS http://192.168.2.1:9000/ws/login Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin. 

我真的很迷茫...任何建议将不胜感激!

【问题讨论】:

标签: javascript json angularjs cors angular-http


【解决方案1】:

我已经成功启动并运行了 CORS 设置。

因为我们使用的是 Play!框架和现代浏览器在发送真正的 POST 方法之前发送一个 OPTION 方法,以在某种程度上“预授权”发送 CORS 请求。

http://better-inter.net/enabling-cors-in-angular-js/ 中所述,我必须添加

        $http.defaults.useXDomain = true;

在实际 $http.post 之前,但我不必删除 'Content-Type' 标头


如果您曾经使用过类似的设置,我建议您查看以下资源:

Play 2.0.1 and setting Access-Control-Allow-Origin
Play! 2.0 easy fix to OPTIONS response for router catch-all?

【讨论】:

    【解决方案2】:

    正如亚当所说!

    如果你使用的是 apache:

     Header set Access-Control-Allow-Origin:  http://domain.com, http://localhost/
    

    或者只是

    Header set Access-Control-Allow-Origin: *
    

    这样做只是为了测试。对于生产,将来源限制为仅您的域。

    【讨论】:

    • @Adam 实际上这是一个 SAME-ORIGIN 问题,第一个 404 误导了我。但是,我需要以某种方式处理这个问题,因为我的案例不可能拥有 Web 服务和相同的 Angular 服务器。 ATM 我正在​​使用 python SimpleHTTPServer 来测试我的 Angular 应用程序,但我怀疑我是否可以配置 ORIGIN 标头。可以抑制标头发送或类似的东西(正如亚当建议的 django)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多