我試圖從一個使用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