2015-12-30 103 views
-2

我想做一個AngularJS $ http請求函數,它將從服務器端調用此方法(使用JAX-RS Jersey),此方法爲參數使用JSON並返回JSON作爲結果,

@Path("/login") 
@POST 
@Consumes(value = MediaType.APPLICATION_JSON) 
@Produces(value = MediaType.APPLICATION_JSON) 
public Response login(User user) { 
    UserDao ud = new UserDao(); 
    User dariDB = ud.login(user.getUsername(), user.getPassword()); 
    dariDB.setPassword(""); 
    return Response.ok(dariDB) 
      .header("Access-Control-Allow-Origin", "*") 
      .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization") 
      .header("Access-Control-Allow-Credentials", "true") 
      .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD") 
      .header("Access-Control-Max-Age", "1209600") 
      .build(); 
} 

你能幫助我在AngularJS假設Web服務的URL給了個例子,$http請求功能是「http://localhost:8084/iec3/rest/user/login」?

+0

你能告訴到目前爲止,你已經嘗試了什麼? – h7r

+0

HTTP({ \t \t \t \t方法: 'POST', \t \t \t \t URL: 'HTTP://本地主機:8084/IEC3 /休息/用戶/登錄', \t \t \t \t \t \t \t \t數據:{ \t \t \t \t \t \t尼姆:scope.nim, \t \t \t \t \t \t通:scope.pass, \t \t \t \t \t \t \t \t \t \t}, \t \t \t \t頭:{ \t \t \t \t \t \t '內容類型': '應用/ JSON' , \t \t \t \t \t \t} \t \t \t \t})然後(函數successCallback(響應){ \t \t \t \t \t \t的console.log(response.data); \t \t \t \t \t \t},功能errorCallback(響應){ \t \t \t \t \t \t \t Flash.create( '危險', '什麼錯在這裏', '定製級'); \t \t \t \t \t \t \t console.log(response。數據); \t \t \t \t \t}); 但我得到了錯誤 –

+0

服務器響應到底是什麼?角碼是從同一個localhost:8084加載的? – h7r

回答

4

您可以對服務器的請求,像下面的代碼片段:

$http({ 
     method: 'POST', 
     url: 'http://localhost:8084/iec3/rest/user/login' 
     data: user 
    }) 

控制器A完整的例子如下:

$scope.login = function() { 
    $http({ 
     method: 'POST', 
     url: 'http://localhost:8084/iec3/rest/user/login' 
     data: user 
    }).then(function(response) { 
     console.log(response); 
    }, function(error) { 
     console.log(error); 
    }); 
}; 
+0

中的角碼加載我已經嘗試了代碼,但控制檯返回錯誤狀態= 0,你知道爲什麼嗎? –

+0

也許你的請求被取消了。這就是爲什麼狀態爲零的原因。你確定http:// localhost:8084/iec3/rest/user/login是否正常工作?你有測試嗎? –

+0

我已經嘗試使用郵遞員應用程序localhost:8084/iec3/rest/user/login並正常工作,我剛發現新問題,如果我嘗試發送無需參數的請求,請求成功,但如果使用參數請求失敗,你知道爲什麼嗎? –