HTTP拦截器头

时间:2017-11-23 08:52:40

标签: angular http http-headers interceptor

我每次尝试发送http请求/帖子时都尝试发送特定的标头。但我的问题是,我不知道我的拦截器是否真的有效。有没有办法让我查看我用http发送的标题?

//发送http的服务

getTokenFromServer(data: Authentication): Observable <string>{
    //const serverUrl = 'http://localhost/broadcast-mock-server/getToken.php';
    const serverUrl = 'http://localhost:5000/token';

    const headers = new HttpHeaders();
    headers.append("Content-Type", "application/json");

    const obs = new Subject<string>();

    const formData = new FormData();
    formData.append('broadcasttoken', '769bcc1c-eba1-4425-a711-a7619d0ab3f1');

    formData.append('displayname', data.name);
    formData.append('password', data.password);

    this.http.post(serverUrl, formData, {headers: headers})
    .subscribe((response: Response) => { 

        if(response){
            console.log("Status:" +response.status);
            console.log("Message", response);               
            this.tokenService.setToken(response["access_token"]);
            return obs.next(response["access_token"]);
        }
    }, (error) => {
        console.log("Error code from server: " +error.status, error);
    });
    return obs.asObservable();

}

拦截每个http请求的拦截器

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        const authHeader = this.tokenService.getToken();
        // Clone the request to add the new header.
        if(req["url"].indexOf("/token") > -1 || req["url"].indexOf("/authenticate") > -1){
            //Don't add Authorization header
            return next.handle(req);
        }else{
            if(!authHeader){
                const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
                return next.handle(authReq);
            }else{
                //Go to /authenticate
                const secureReq = req.clone({url: req.url.replace('http://', 'https://localhost:5000/authenticate')});
                return next.handle(secureReq);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

只需检查浏览器检查器

即可

enter image description here

如果你想通过控制台,你可以打电话:

net.corda.core.testing

答案 1 :(得分:0)

最简单的方法是检查浏览器开发工具。

但您使用的代码可能无效。

const headers = new HttpHeaders();
headers.append("Content-Type", "application/json");

HttpHeaders是一个不可变对象,你需要将标题追加到它后面

像这样:

let headers = new HttpHeaders();
headers = headers.append("Content-Type", "application/json");