如何在 react-native 中为 webView 请求设置自定义标头 [英] How to set a custom header for webView requests in react-native
问题描述
我希望能够在我的 ruby on rails 服务器端检测到 http 请求来自我的应用程序中的 webView 组件.该应用程序正在使用 react-native.特别是,我想区分来自应用程序的请求和来自在 ios 设备上运行的移动 safari 的请求.
I want to be able to detect on my ruby on rails server side that a http request has come from a webView component in my app. The app is using react-native. In particular, I want to distinguish between a request from the app and a request from mobile safari running on an ios device.
我尝试在 AppDelegate.m
文件中设置以下内容
I have tried setting the following in the AppDelegate.m
file
NSURL *url = [NSURL URLWithString:@"http://localhost:3000/signin"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request addValue:@"GolfMentor" forHTTPHeaderField:@"User-Agent"];
[request addValue:@"GolfMentor" forHTTPHeaderField:@"X-MY-CUSTOM-HEADER"];
NSLog(@"%@", [request allHTTPHeaderFields]);
并且控制台中的输出是
GolfMentor[63924:12437749] {
"User-Agent" = GolfMentor;
"X-MY-CUSTOM-HEADER" = GolfMentor;
}
因此客户标题似乎已设置.但是,当我在 ruby on rails 应用程序中查看请求标头时,没有自定义标头的迹象.看起来我的更改在执行本机应用程序时被覆盖.那么我应该在哪里以及如何设置自定义标题?我也有兴趣为该应用的 android 版本做同样的事情?
So the customer header appears to be set. However, when I view the request header in my ruby on rails app, there is no sign of the custom header. It looks like my changes are being overwritten latter in the execution of the react-native app. So where and how should I set the custom header? I am also interested in do the same thing for an android version of the app?
推荐答案
尝试将以下几行添加到 AppDelegate.m 以设置自定义用户代理
Try adding the following lines to AppDelegate.m to set the custom user-agent
NSString *newAgent = @"GolfMentor";
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
可以在此处找到更完整的答案和针对 android 的解决方案.
这篇关于如何在 react-native 中为 webView 请求设置自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!