[英]Adding Authentication token to file upload in angular 2
如何向文件上传服务添加身份验证令牌? 当我登录我的应用程序时,我能够从后端检索令牌,但我很难确定如何将其添加到文件服务。 当我尝试上传文件时,出现错误消息“ token_not_provided”。 由于它在我的服务中,因此我已经在标头中添加了身份验证令牌,因此,每当我发出请求时,服务器就会知道手边的用户。 但是对于文件提交,我不知道如何将身份验证令牌附加到文件服务
@Component({
providers:[AuthenticationService]
})
@Injectable()
export class FileUploadService {
public progress$;
public progressObserver;
public progress : number;
public token: string;
public headers:string;
constructor (private auth:AuthenticationService) {
this.progress$ = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
makeFileRequest (url: string, params: string[], files: File[]) {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.setRequestHeader(this.headers, this.auth.token);//modified
xhr.send(formData);
});
}
}
//service
updateFood(food:any) {
const body = JSON.stringify(food);
const headers = new Headers({ 'Authorization': 'Bearer ' + this.authenticationService.token });
return this.http.put('http://localhost:9000/, body, {headers: headers})
.map((data:Response) => data.json());
}
您可以在xhr.open
和xhr.close
之间的xhr.open
xhr.close
附加标题
xhr.setRequestHeader(header, value);
有关更多详细文档,请参见https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.