【问题标题】:Chrome cancels Angular 2 requestChrome 取消 Angular 2 请求
【发布时间】:2016-12-30 03:09:43
【问题描述】:

我正在编写一个调用本地主机上的 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>

那么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);
        });  
}

然后在 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'))
}

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

最后是取消的请求标头:

想法?

【问题讨论】:

    标签: google-chrome angular


    【解决方案1】:

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

    例如:

    <!-- Added button 'type' attribute/value -->
    <button type="button" tabindex="12"...
    

    MDN Documentation

    引用自W3Schools

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

    【讨论】:

    • 成功了!我不敢相信,但确实如此:)谢谢史蒂夫
    • 没问题。很高兴我能帮上忙!
    • 花了很长时间才来到这里。这个答案可以救命:)
    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多