?今日需求:
? ? ? ? ?獲取用戶(hù)ip地址,并在每一次請(qǐng)求的時(shí)候帶上這個(gè)ip地址
1、如何獲取用戶(hù)IP地址:
獲取 用戶(hù)ip地址的方式有很多,各大地圖的開(kāi)發(fā)者平臺(tái)都能找到相關(guān)的API接口地址,都很牛掰,但是我看了一下,好像不太適合我(懶病犯了~~),所以我就用shohu的接口:
http://pv.sohu.com/cityjson?ie=utf-8
uni.request({
url: '/sohu/cityjson',
success: (res) => {
const reg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
let ip = reg.exec(res.data);
// console.log(ip)
// console.log(res.data)
// console.log(ip[0]);
uni.setStorage({
key: 'ip',
data: reg.exec(res.data),
success: function() {
// console.log('success');
},
});
}
});
? ? ? ?當(dāng)時(shí)想的思路很簡(jiǎn)單,直接用接口地址訪(fǎng)問(wèn)獲取ip就可以了,因?yàn)槲沂茿PP和H5都需要開(kāi)發(fā)。這樣的話(huà)很顯然,H5端必會(huì)出現(xiàn)跨域問(wèn)題,所以我就使用了proxy解決了跨域問(wèn)題。
2、跨域問(wèn)題的解決
"devServer" : {
"port" : 8000,
"disableHostCheck" : true,
"proxy" : {
"/sohu" : {
"target" : "http://pv.sohu.com",
"changeOrigin" : true,
"secure" : false,
"pathRewrite" : {
"^/sohu" : ""
}
}
}
}
3、如何返回給后端
???很簡(jiǎn)單對(duì)吧!
拿到存儲(chǔ)中保存的key就行了,直接放在接口請(qǐng)求頭之中。但是,數(shù)據(jù)并沒(méi)有傳過(guò)去,APP端不適用這種方式。如果需要同時(shí)滿(mǎn)足app和H5的話(huà)就需要用到條件編譯
以下是完整的app和H5分別獲取的ip地址的方式:
//#ifdef H5
//只執(zhí)行h5
uni.request({
url: '/sohu/cityjson',
success: (res) => {
const reg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
let ip = reg.exec(res.data);
console.log(ip)
// console.log(res.data)
// console.log(ip[0]);
uni.setStorage({
key: 'ip',
data: reg.exec(res.data),
success: function() {
// console.log('success');
},
});
}
});
//只執(zhí)行h5
// #endif
// #ifdef APP-PLUS
//只執(zhí)行app
uni.request({
url: 'http://pv.sohu.com/cityjson?ie=utf-8',
method: 'POST',
success: (res) => {
const reg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
let ip = reg.exec(res.data);
// console.log(ip[0]);
uni.setStorage({
key: 'ip',
data: reg.exec(res.data),
success: function() {
// console.log('success');
},
});
}
})
//只執(zhí)行app
// #endif
完美解決~~?
然后將保存的數(shù)據(jù),在你的接口工具中拿到,放在請(qǐng)求頭中就可以傳給后端了?。。。?/p>
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-507929.html
?然后可以在每一次的請(qǐng)求過(guò)中都能帶上ip地址了!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-507929.html
到了這里,關(guān)于前端獲取用戶(hù)ip地址,并放在請(qǐng)求頭上(uniapp和H5)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!