前言
在我们使用JWT来做用户的验证时,我们登陆生成对应的token,并加入到请求的参数中发送到后台提供相关的权限校验。这个时候我们需要使用到传递请求头参数传递的问题,下面是两种方式。
1.ajax提交方式
1).方法一:
$.ajax({
type: "GET",
url: "/access/logout/" + userCode,
headers: {'Authorization': token}
});
上面的方法一是我提交的方式
请求成功后
$.ajax({
type: "GET",
url: "/access/logout/" + userCode,
beforeSend: function(request) {
request.setRequestHeader("Authorization", token);
},
success: function(result) {
}
});
2.anjular添加token到header中的方式
1.自定义Http方法,全局使用自动添加Token到Header中,或者使用拦截器,方法类似。
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {
Http,
RequestOptionsArgs,
RequestOptions,
Response,
Headers
} from '@angular/http';
const mergeToken = (options: RequestOptionsArgs = {}) => {
const newOptions = new RequestOptions({}).merge(options);
const newHeaders = new Headers(newOptions.headers);
const jwt = localStorage.getItem('jwt');
if (jwt) {
newHeaders.set('Authorization', jwt);
}
newOptions.headers = newHeaders;
return newOptions;
};
@Injectable()
export class MyHttp {
constructor(private http: Http) {
}
get(url: string, options?: RequestOptionsArgs): Observable
return this.http.get(url, mergeToken(options));
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable
return this.http.post(url, body, mergeToken(options));
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable
return this.http.put(url, body, mergeToken(options));
}
delete(url: string, options?: RequestOptionsArgs): Observable
return this.http.delete(url, mergeToken(options));
}
patch(url: string, body: any, options?: RequestOptionsArgs): Observable
return this.http.patch(url, body, mergeToken(options));
}
head(url: string, options?: RequestOptionsArgs): Observable
return this.http.head(url, mergeToken(options));
}
}