2016-09-19 46 views
0

我爲登錄創建了一個頁面,但發佈的請求有問題。 我使用最終版本角2Angular 2發佈請求返回404服務

的login.html

<label for="username">User</label> 
<input type="text" id="user" #user> 
<label for="password">Password</label> 
<input type="password" id="password" #password> 
<button type="submit" (click)="onLogin(user.value, password.value); user.value=''; password.value=''">Login</button> 

login.ts

@Component({ 
selector: 'login', 
templateUrl: 'app/views/login.html', 
providers: [ LoginService ], 
styleUrls: [ 'css/login.css' ] 
}) 
export class Login extends Locale { 
users: User[]; 

constructor(public localization: LocalizationService, 
      private _loginService: LoginService) { 
    super(null, localization); 
} 

    onLogin(username: string, password: string) { 
    if (!username && !password){return;} 
    this._loginService.login(username, password) 
     .subscribe(
      user => this.users.push(user), 
      error => console.log(error), 
      () => console.log("Complete") 
     ); 
    } 
} 

user.ts

export class User { 
constructor(
    public username: string, 
    public password: string) {} 
} 

user.servece.ts

@Injectable() 
export class LoginService { 
// URL to web api 
private loginUrl = './authenticate'; 

constructor (private http: Http) {} 

login (username, password): Observable<User> { 
    var body = `username=${username}&password=${password}`; 
    var headers = new Headers(); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    var options = new RequestOptions({ headers: headers }); 

    console.log("Url: "+this.loginUrl); 
    console.log("body: " + body); 
    console.log("headers: "+headers); 

    return this.http.post(this.loginUrl, body, options) 
     .map(this.extractData) 
     .catch(this.handleError); 
} 

private extractData(res: Response) { 
    let body = res.json(); 
    return body.data || { }; 
} 

private handleError (error: any) { 
    // In a real world app, we might use a remote logging infrastructure 
    // We'd also dig deeper into the error to get a better message 
    let errMsg = (error.message) ? error.message : 
     error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
    console.error(errMsg); // log to console instead 
    return Observable.throw(errMsg); 
} 
} 

我有錯誤: POST http://localhost:3000/authenticate 404(未找到)

的數據必須被髮送輸入和存儲在一個JSON-文件鏈接時,這將是本地主機:3000 /驗證。

有什麼不對,請幫忙!

+0

服務器不接受連接在這個URL +端口 –

回答

0

您正在發佈數據到http://localhost:3000/authenticate哪個好。您沒有任何代碼可以接受任何發佈日期。您應該爲使用您的數據的http://localhost:3000/authenticate提供REST服務。請參閱如何爲您所需的語言開發REST服務。

+0

我不創建/認證頁面,它必須在我的Java Servlet API中創建,但我不明白它必須如何實現 –

+0

你可以使用post-man chrome插件測試http:// localhost:3000/authenticate。使用post man插件可以POST,GET,PUT和DELETE http請求。使用http方法檢查你的API,如果它工作,然後嘗試使用代碼。 –

+0

謝謝,非常好的插件。但我仍然得到404 –