2017-07-23 45 views
0

Postman header不能在Angular2

Postman body

所以我想在我的角度申請認證後獲得工作。我參加了標題並創建了一個字符串化的主體。我也看了一些有關在郵遞員發送郵件請求的其他論壇帖子,但我無法得到它的工作。

getToken() 
{ 
    console.log('started getting of token'); 

    //get username and password from local storage 

    //Send username and password via body 

    let headers = new Headers(); 
    let body = JSON.stringify({ 
     name: 'test', 
     password: 'test' 
    }); 

    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

    this.jwt = this.http.post('http://localhost:8080/api/authenticate/', { 
     headers: headers, 
     body: body 
    }).map(res => res.text()).subscribe(data => console.log(data)); 

} 

所以上面是我的代碼。我知道這可能是一件有點愚蠢的事情,但我無法得到它的工作。 我收到用戶無法找到的錯誤。當用戶名錯誤,以及用戶名不存在於數據庫中時會發生這種情況。所以還有一點棘手。

誰知道我犯了什麼愚蠢的錯誤?

+0

嘗試' '的Content-Type':「應用程序/ json'' –

+0

難道不幸的是不行的,感謝您的建議:) – Nathan

+0

調試你的API,檢查你的名字和密碼參數。 –

回答

0

在service.ts文件添加該代碼。

import { Http, URLSearchParams} from '@angular/http'; 
    getToken() 
    { 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    let body = new URLSearchParams(); 
    body.set('name', test); 
    body.set('password', test); 
    return this.http.post("http://localhost:8080/api/authenticate/", body, headers).map(response => response.json()); 
    } 
+0

這實際上是工作。謝謝! – Nathan

0

使用下面的代碼來發送POST請求

this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data)); 
+0

這樣做會導致我的空身。 – Nathan

+0

你只替換了'this.jwt = ...'這一行,對吧? –

+0

是的,我認爲api出了問題。所以感謝您的幫助,我會繼續調試。 – Nathan

0

這段代碼是我使用POST請求

send_request_post(url: String, data:{}) 
{ 
    var headerPost = new Headers 
    ({ 
     'Content-Type' : 'application/json ;charset=utf-8' 
    }) 

    return this.http.post(url, JSON.stringify(data), {headers: headerPost}) 
    .toPromise() 
    .then 
    (
     response => 
     { 
      console.log(response); 
     } 
    ) 
}