[英]How to distinguish calls from mobile app and web browser in Node Js?
I'm still a bit new to server-side programming, and have decided to start practicing mobile app programming. 我对服务器端编程还是有点陌生,因此决定开始练习移动应用程序编程。 In NodeJS you use the
post
and get
methods, however, I would like to be able to distinguish if a mobile app requested (to send it JSON instead of HTML) or if a web browser requested (to send it HTML) a page. 在NodeJS中,您使用
post
和get
方法,但是,我希望能够区分移动应用程序是否请求(发送JSON而不是HTML)或网页浏览器请求(发送HTML)页面。
How do you do this? 你怎么做到这一点?
Do you achieve this by having separate urls (one for the apps and one for the browsers)? 您是否通过使用单独的网址(一个用于应用程序,一个用于浏览器)来实现此目的? If so, I would like a bit of explanation.
如果是这样,我想解释一下。
Thank you! 谢谢!
You haven't said how you're building your server-side app, but the normal way to do this is using the 'user agent' indicated by the client. 您尚未说过如何构建服务器端应用程序,但通常的方法是使用客户端指示的“用户代理”。
If you're using express, there are modules that make this easy, like https://www.npmjs.com/package/express-useragent 如果您使用的是Express,则有一些模块可以简化此过程,例如https://www.npmjs.com/package/express-useragent
Which gives you a structure that includes a field isMobile
in req
parameter: 这为您提供了一个结构,该结构在
req
参数中包含一个字段isMobile
:
// req.useragent
{
"isMobile":false,
"isDesktop":true,
"isBot":false,
.....
"browser":"Chrome",
"version":"17.0.963.79",
"os":"Windows 7",
"platform":"Microsoft Windows",
"source":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79..."
}
Short answer is you can't determine it from the server side . 简短的答案是您不能从服务器端确定它 。
You need to add an additional parameter to your request, say client: 'app'
or client: 'browser'
and read that param in the server side and send your appropriate response. 您需要在请求中添加一个附加参数,例如
client: 'app'
或client: 'browser'
然后在服务器端读取该参数,然后发送适当的响应。
Something like this will work 这样的事情会起作用
app.get('/endpoint', function (req, res) {
const shouldSendJSON = req.query.client && req.query.client === 'app'
if (shouldSendJSON) {
res.json({data: 'whatever you want to send'})
}
res.send('hello world')
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.