Angular 2 Post请求从服务返回404

时间:2016-09-19 13:46:01

标签: angular http-post

我创建了一个登录页面,但是发帖请求有问题。 我使用最终版Angular 2

的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文件中,该文件将在链接localhost:3000 / authenticate时使用。

出了什么问题,请帮忙!

1 个答案:

答案 0 :(得分:0)

您正在将数据发布到http://localhost:3000/authenticate,这没关系。你没有任何代码接受任何发布日。您应该使用http://localhost:3000/authenticate的REST服务来消耗您的数据。请参阅如何为您所需的语言开发REST服务。