[英]HTTP interceptor headers
I'm trying to send in a specific header every time I'm doing a http request/post. 我每次执行HTTP请求/发布时都尝试发送特定的标头。 But my problem is that I don't know if my interceptor actually works. 但是我的问题是我不知道我的拦截器是否真正起作用。 Is there a way for me to check what headers I'm sending with my http? 有什么方法可以检查我通过http发送的标头吗?
//Service to send 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();
}
Interceptor that intercepts every http request 拦截每个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);
}
}
}
The easiest way would be to check is in the browser dev tools. 最简单的方法是在浏览器开发工具中进行检查。
But the code you are using is probably not working. 但是您使用的代码可能无法正常工作。
const headers = new HttpHeaders();
headers.append("Content-Type", "application/json");
HttpHeaders is an immutable object you need to assign the headers append back to it HttpHeaders是一个不可变的对象,您需要为其分配附加的标头
Like this: 像这样:
let headers = new HttpHeaders();
headers = headers.append("Content-Type", "application/json");
Use dev tools provided by the different browser: 使用不同浏览器提供的开发工具:
Internet Explorer Developer Tools Internet Explorer开发人员工具
Example for Chrome : Chrome的示例 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.