我试图从一个使用Angular JS的web服务得到响应,我可以通过我的shell使用简单的curl命令完全实现:
curl --header "Content-type: application/json" --request POST
--data '{"username": "name", "password": "pwd"}' 192.168.2.1:9000/ws/login
但是,当我尝试使用Angular与$http.post
达到它时,我会遇到一些“有趣”的行为。
虽然我的数据是:
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://
的网址,而不是,给我:
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.
我真的真的失去了...任何建议,将不胜感激!
如果您在发布帖子的同一个框中本地运行服务器,该怎么办?你有没有尝试过不添加'header'? –
我想你自己回答了这个问题... 选项http://192.168.2。1:9000/ws/login访问控制 - 允许来源不允许原始http:// localhost:9000。 当您的角度应用在http:// localhost:9000上运行时,您的Web服务运行在http://192.168.2.1:9000上。您无法将AJAX请求发送到其他站点(scheme:host:port的组合)。在这里阅读更多: https://en.wikipedia.org/wiki/Same-origin_policy 你可能需要做这样的事情: http://better-inter.net/enabling-cors-in- angular-js/ – Adam