【发布时间】: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.
我真的很迷茫...任何建议将不胜感激!
【问题讨论】:
-
如果您在发布帖子的同一机器上本地运行服务器会怎样?你试过不加
headers吗? -
我想你自己回答了这个问题... OPTIONS 192.168.2.1:9000/ws/login Origin localhost:9000 是 Access-Control-Allow-Origin 不允许的。您的 Web 服务在 192.168.2.1:9000 上运行,而您的 Angular 应用程序在 localhost:9000 上运行。您不能向其他站点发出 AJAX 请求(方案:主机:端口的组合)。在这里阅读更多:en.wikipedia.org/wiki/Same-origin_policy你可能需要做这样的事情:better-inter.net/enabling-cors-in-angular-js
标签: javascript json angularjs cors angular-http