2016-09-20 44 views
0

我是Angular2中的新成員。我正在嘗試從Angular2調用簡單的Java REST調用。當我發佈數據時,我根本沒有收到錯誤,但是我的java post方法沒有被調用。POST方法不適用於Angular2

Angular2 POST-

let emplyee = JSON.stringify(this.object); 
    let url = 'http://localhost:8080/rest-app/rest/employeeService/insertEmployee'; 
    console.log("Data: " + emplyee); 
    let headers = new Headers({'Content-Type': 'application/json'}); 
    let options = new RequestOptions({headers: headers}); 
    this.http.post(url, emplyee, options); 

Java的POST方法 -

@POST 
@Path("/insertEmployee") 
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(MediaType.APPLICATION_JSON) 
public String insertEmployee(String employee) { 
    logger.debug("Employee: " + employee); 
    return "Hello"; 
} 
+0

你得到的迴應是什麼?在'this.http.post()'後面加'.subscribe(res => console.log(res))到'console.log'這個響應。 – Supamiu

+0

@Supamiu thnx for response,我收到了這個迴應,**對預檢請求的響應沒有通過訪問控制檢查:在請求的資源上沒有「Access-Control-Allow-Origin」標頭。因此不允許訪問Origin'http:// localhost:3000'。** – deen

回答

1

這裏的問題在於預檢請求不通過。 您必須在您的Java API中允許CORS請求(您必須添加Access-Control-Allow-Origin *標頭,請參閱您的API庫文檔以瞭解如何添加它)。

這就是爲什麼在訂閱時出現錯誤,因爲您的預檢請求未通過。

編輯:參見How to make CORS-enabled HTTP requests in Angular 2?瞭解更多關於該問題的解釋。

0

您需要添加訂閱喜歡這個 -

this.http.post(url, emplyee, options) 
    .subscribe((response) => { 
      //handle response here 
    }) 
    .catch(this.handleError); 

如果你想使用的承諾,然後使用它像這 -

this.http.post(url, employee, options) 
     .toPromise() 
     .then(this.extractData) 
     .catch(this.handleError); 
相關問題