Navigator.sendBeacon() to pass header information

后端 未结 6 1909
Happy的楠姐
Happy的楠姐 2020-12-06 00:51

I am using navigator for communicating with the server , but problem is that we need to pass some header information as there is filter which recognise the request is from t

6条回答
  •  伪装坚强ぢ
    2020-12-06 01:00

    Because the method sendBeacon(..) does not allow headers manipulation, I added them into the form as normal fields:

        const formData = new FormData();
        formData.append('authorization', myAuthService.getCachedToken());
        navigator.sendBeacon(myURL, formData);
    

    Then on the host side I added a simple Middleware class (.Net) which catches POST requests without headers and copies them from the body:

        public class AuthMiddleware
        {
            ...
            ...
            public async Task Invoke(HttpContext context)
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader == null && context.Request.Method=="POST")
                {
                    context.Request.Headers["Authorization"] = string.Format("Bearer {0}",
                        context.Request.Form["authorization"].ToString());
                }
    
                await _next.Invoke(context);
            }
        }
    

提交回复
热议问题