gpt4 book ai didi

javascript - 如何在 Angular 拦截器中向请求主体添加内容?

转载 作者:可可西里 更新时间:2023-11-01 02:22:36 25 4
gpt4 key购买 nike

这里我可以修改标题,因为有多个关于此功能的教程,但是:

@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {

constructor(private currentUserService: CurrentUserService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(JSON.stringify(req));

const token: string = this.currentUserService.token;

if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}

if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}

req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req);
}
}

但在我的例子中,有一个 token ,我需要添加请求正文而不是请求 header ,所以有没有任何方法可以修改正文。

Update: Mild Fuzz's method is working great for a simple post request but I'll like to add to query if it's a GET request and body if it allows to add a body. And most importantly it broke when I tried to send a form data. ...request.body removes the form data and transforms it to a JSONobject so my image is gone.

最佳答案

 req = req.clone({ 
headers: req.headers.set('Accept', 'application/json'),
body: {...req.body, hello: 'world' }});

是这样的吗?

关于javascript - 如何在 Angular 拦截器中向请求主体添加内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53149223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com