[英]Adding Authentication token to file upload in angular 2
How can i add authentication token to the file upload service? 如何向文件上传服务添加身份验证令牌? When i login in my application, i am able to retrieve the token from the backend but i am having a hard time as to how to add it the to file service. 当我登录我的应用程序时,我能够从后端检索令牌,但我很难确定如何将其添加到文件服务。 When i try to upload a file, it get an error saying "token_not_provided". 当我尝试上传文件时,出现错误消息“ token_not_provided”。 As it is in my service, i have added the authentication token in my header so whenever i make a request, the server is aware of the user at hand. 由于它在我的服务中,因此我已经在标头中添加了身份验证令牌,因此,每当我发出请求时,服务器就会知道手边的用户。 But with the file submission, i have no idea of how to append the authentication token to the file service 但是对于文件提交,我不知道如何将身份验证令牌附加到文件服务
@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());
}
Somewhere between your xhr.open
and xhr.close
you can append headers 您可以在xhr.open
和xhr.close
之间的xhr.open
xhr.close
附加标题
xhr.setRequestHeader(header, value);
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader for more detailed documentation 有关更多详细文档,请参见https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.