如何解决Angular 9-如何正确编码+登录URL参数
我花了很多小时没有成功。我知道这是一个普遍的问题,有许多解决方案,但对我来说,我只能避免使用拦截器。
我的服务-在这里我收到带有john.doe+100@gmail.com之类的加号电子邮件
@Injectable({
providedIn: 'root',})
export class UsersHttpService {
httpParams = new HttpParams({encoder: new CustomEncoder()});
removeUsersFromGroup(groupId: string,email: string): Observable<any> {
console.log(email); //john.doe+100@gmail.com
let parsedEmail = encodeURI(email); //one of many attempts
return this.http.delete(`${this.env.URI}/monitoring/api/v1/groups/${groupId}/users/`,{
params: {
groupId,email: email.replace(' ','+')
},});
}
还有我的CustomEncoder:
export class CustomEncoder implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
// console.log('encodeValue encodeValue');
// console.log(value);
// console.log(encodeURIComponent(value));
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
// console.log('decodeValue decodeValue');
// console.log(value);
// console.log(decodeURIComponent(value));
return decodeURIComponent(value);
}
}
当我从Angular发送请求时,然后在Web浏览器的“网络”标签中看到:
DELETE https://myapp/groups/d39a4f50-8ebd-11ea-a9ae-5103b15ad73b/users/?groupId=d39a4f50-8ebd-11ea-a9ae-5103b15ad73b&email=john.doe 100@gmail.com
带有空格!怎么了?是问题吗?在控制台中,我收到带有+的电子邮件,但在“网络”选项卡中没有空格而不是+符号。
仅当我使用全局拦截器(应避免)时,我的参数才正确编码(后端(春季启动)有200个状态,带有+的电子邮件):
import {
HttpEvent,HttpHandler,HttpInterceptor,HttpParams,HttpRequest,} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
import {CustomEncoder} from "./customEncoder";
@Injectable()
export class EncodeHttpParamsInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
const params = new HttpParams({
encoder: new CustomEncoder(),fromString: req.params.toString(),});
return next.handle(req.clone({params}));
}
}
有人有任何想法吗???我尝试使用:
返回this.http.delete(${this.env.ORBITAL_URI}/monitoring/api/v1/groups/${groupId}/users/
,{
参数:{
groupId,
电子邮件:encodeURI(email)//或encodeURIComponent(email)
},
});
然后在[网络]标签中看到类似john.doe%2B%40gmail.com的内容,但后端出现500错误
解决方法
我的解决方案-没有任何拦截器:
removeUsersFromGroup(groupId: string,email: string): Observable<any> {
const params = new HttpParams({
encoder: new CustomEncoder(),fromObject: {
groupId,email,},});
return this.http.delete(`${this.env.URI}/myapp/v1/groups/${groupId}/users/`,{
params: params,});
}
现在它可以正常工作了:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。