javascript - 在 Angular 2 中提交发布请求时的奇怪行为

标签 javascript angular typescript cors angular2-http

我知道我的标题有点含糊,但这是我的情况。我刚刚启动了一个应用程序,我在其中实现 JWT 进行身份验证。我已经设置了服务器端,并且可以验证它是否按预期工作。

奇怪的是,当你点击按钮登录时,在 Chrome 和 Firefox 中它只发送一次请求,没有请求的正文。在 Edge 中,它会提交两次,一次是像 Chrome 一样,然后第二次几乎是在 body 完好无损之后。

我现在将登录名直接硬编码到发布请求中,以尝试消除尽可能多的东西。

header.component.html

<ul id="links">
    <li>
        <a href="/">Home</a>
    </li>
    <li>
        <a href="/census">Census</a>
    </li>
    <li>
        <button (click)="login()">Login</button>
    </li>
</ul>

header.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthenticationService } from '../_services/Authentication.Service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor(private _auth: AuthenticationService, private router: Router) { }

  ngOnInit() {
  }

  login() {
        this.loading = true;
        this._auth.login(this.model.username, this.model.password)
            .subscribe(result => {

            });
    }

}

Authentication.Service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
 
@Injectable()
export class AuthenticationService {
    public token: string;
 
    constructor(private http: Http) {
        // set token if saved in local storage
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }
 
    login(usn: string, psw: string): Observable<boolean> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post('http://localhost:5000/auth', JSON.stringify({ username: "email-removed", password: "password-removed" }), options)
                    .map((response: Response) => { return true; });
    }
}

这是我从 Chrome 看到的第一个请求的请求,响应为空

Request URL:http://localhost:5000/auth
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:8888
Response Headers
view source
Allow:POST, OPTIONS
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Sat, 31 Dec 2016 00:08:05 GMT
Server:Werkzeug/0.11.13 Python/3.5.2
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8,es;q=0.6
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Host:localhost:5000
Origin:http://localhost:4200
Proxy-Connection:keep-alive
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

这是 fiddler 捕获的第二个请求。当我点击 chrome 中的按钮时,它永远不会发生

POST http://localhost:5000/auth HTTP/1.1
Accept: */*
content-type: application/json
Referer: http://localhost:4200/
Accept-Language: en-US,en;q=0.8,zh-Hans-CN;q=0.7,zh-Hans;q=0.5,es-US;q=0.3,es;q=0.2
Origin: http://localhost:4200
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393
Content-Length: 58
Host: localhost:5000
Connection: Keep-Alive
Pragma: no-cache

{"username":"removed","password":"removed"}

第二个的响应

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0ODMxNDE5NDIsImlkZW50aXR5IjoiNTg2NmJiNDkwYzE3ZDdlMzk4MTk5MWNhIiwiZXhwIjoxNDgzMTQyMjQyLCJuYmYiOjE0ODMxNDE5NDJ9.VZGBYnPKPwyR0lWdG3kR8AecbLNlYCHMC1nimAHeP3w"
}

这是给你的另一个奇怪/线索。后端是 Python/Flask rest。当我看到请求进来时,这就是我所看到的。那些说 OPTIONS 的是空请求,那些说 POST 的是仅在 Edge 中发生并且正确的第二个请求。 enter image description here

最佳答案

确保在您调用的路由末尾有一个斜线。所以不要打电话

'http://localhost:5000/auth'

你的目标

'http://localhost:5000/auth/'

希望这对您有所帮助。

关于javascript - 在 Angular 2 中提交发布请求时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404170/

相关文章:

gruntjs - TypeScript 编译器在 Mac 上失败

javascript - ESLint 是否可以对脚本标记的属性类型为 ="text/worker"的 html 文件进行 lint 处理?

javascript - Vue.js 有没有办法在使用 v-for 时生成分隔符(类似于 `Array.join()` FreeMarker 的 `<#sep>` )

Angular 表单验证如何在提交时显示错误消息

模型更改时 Angular 4 复选框触发更改事件

pluck 的 TypeScript 定义

javascript - Kurento 媒体服务器 HelloWorld Javascript 示例 webSocket 错误

javascript - 如何同时使用模式和需求进行电子邮件字段验证?

angular - 使用 PrimeNG 组件的 CLI 构建

node.js - Angular 6 - 删除node_module包并将其用于本地项目更改