Chrome 取消了 Angular 2 请求

MAK*_*020 1 google-chrome angular

我正在编写一个调用本地主机上的 PHP api 的 Angular 2 应用程序。login.component.html 中的 HTML如下:

<form name="loginForm" class="loginForm">

    <input type="text" name="email" id="email" placeholder="Email" [(ngModel)]="model.email" size="65">

    <input type="password" name="password" id="password" placeholder="Password" [(ngModel)]="model.password" class="input" size="20">

    <button tabindex="12" class="btn-full submit" (click)="attemptLogin()">Log In</button>
</form>
Run Code Online (Sandbox Code Playgroud)

然后login.component.ts有attemptLogin() 函数:

attemptLogin(){
    this.identityService.attemptLogin(this.model).subscribe(
        result => {
            if(result.isauthenticated){
                console.log('Successful Auth');
            }else {
                console.log('Failed Auth');
            }
        }, 
        err => {
            console.log(err);
        });  
}
Run Code Online (Sandbox Code Playgroud)

然后在identityService.ts我有:

attemptLogin(credentials: Credentials): Observable<Authorization> {

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    let bodyString = JSON.stringify(credentials); 


    return this.http.post('http://localhost:8000/login', bodyString, options)
        .map((res:Response) => res.json())
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
}
Run Code Online (Sandbox Code Playgroud)

我确保后端 php 正在工作并返回有效响应。我的问题是 chrome 取消了请求,IE 相同,但 Firefox 确实可以工作并成功返回响应。这在某些时候有效,我最近更新了 chrome,这可能与它有关。我还确保这不是 CORS 问题,因为它在更新之前确实可以在 chrome 中工作,并且在 Mozilla 中也可以正常工作。这是 Chrome 的响应:

在此处输入图片说明

最后是取消的请求标头: 在此处输入图片说明

想法?

Ste*_*mez 5

我最初的猜测是您需要将type="button"属性/值添加到按钮标记中。Chrome 中按钮标签的默认行为是提交表单,这会取消您的请求(当浏览器将表单发送回自身时)。

例如:

<!-- Added button 'type' attribute/value -->
<button type="button" tabindex="12"...
Run Code Online (Sandbox Code Playgroud)

MDN 文档

引自W3Schools

提示:始终为<button>元素指定类型属性。不同的浏览器对<button> 元素使用不同的默认类型。