[英]Angularjs $http.get method not working
我在端口8501上運行微服務。
@RestController
@RequestMapping("/feeds")
public class FeedsController {
@RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds() {
return new ResponseEntity<String>("Hello", OK);
}
}
當我添加url http://localhost:8501/feeds
,瀏覽器顯示“Hello”。 現在我試圖通過angularjs獲取調用來訪問它
在我的AngularJs我的代碼是
'use strict';
var app = angular.module('commentsjsApp');
app.controller('MainCtrl', function ($scope,$http) {
$http.jsonp('http://localhost:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data+ "Status");
}).error(function(){
console.debug("error");
});
編輯:在網絡選項卡(firebug)中,我可以看到GET具有200狀態,響應為“Hello”。 為什么我在控制台中收到錯誤呢? 任何人都可以幫助我。
當我運行這個angularjs應用程序。 控制台上的以下輸出如圖所示
您正在請求JSONP數據,但服務器正在返回一個string
。 從服務器返回適當的JSON對象以解決問題。
注意 : Hello world
不是有效的JSON,但是"Hello World"
是。
您需要在響應中添加標頭“Access-Control-Allow-Origin”,因為您從localhost:9000調用localhost:8501(它們在技術上是不同的服務器)。
@RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
httpResponse.addHeader("Access-Control-Allow-Origin",
"http://127.0.0.1:9000");
return new ResponseEntity<String>("Hello", OK);
}
有時Angular要求引用URL中的冒號,試試這個:
$http.get('http://localhost\\:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data);
}).error(function(){
console.debug("error");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.