UniApp中APP端使用Web3调用RPC出现跨域问题
推荐web3.js 版本 1.7.4
npm i web3@1.7.4
错误原因: UniApp中APP端使用的XMLHttpRequest对象与Html中的对象是不兼容的, 必须使用H5+原生的对象(plus.net.XMLHttpRequest)
解决办法1: 重写Web3的HttpProvider覆盖并且重新导出
重新web3.js代码如下
let Web3 = require('web3');
Web3.providers.HttpProvider.prototype._prepareRequest = function () {
var request;
// the current runtime is a browser
// #ifdef H5
if (typeof XMLHttpRequest !== 'undefined') {
request = new XMLHttpRequest();
}
else {
request = new XHR2();
var agents = { httpsAgent: this.httpsAgent, httpAgent: this.httpAgent, baseUrl: this.baseUrl };
if (this.agent) {
agents.httpsAgent = this.agent.https;
agents.httpAgent = this.agent.http;
agents.baseUrl = this.agent.baseUrl;
}
request.nodejsSet(agents);
}
// #endif
// #ifdef APP-PLUS
request = new plus.net.XMLHttpRequest;
// #endif
request.open('POST', this.host, true);
request.setRequestHeader('Content-Type', 'application/json');
request.timeout = this.timeout;
request.withCredentials = this.withCredentials;
if (this.headers) {
this.headers.forEach(function (header) {
request.setRequestHeader(header.name, header.value);
});
}
return request;
}
export default Web3
使用web3并查询BNB资产
import Web3 from '@/common/web3.js'
const address = '0x934bb6f7d0c56626131798e77f7fb1cd54c7afb3';
const url = 'https://bsc-mainnet.infura.io/v3/0104c45062a54b75be596e3483fef9ae'
// const url = 'https://bsc-dataseed.binance.org/'
let provider = new Web3.providers.HttpProvider(url);
let web3 = new Web3(provider);
const balance = await web3.eth.getBalance(address);
let balanceFromWei = web3.utils.fromWei(balance, 'ether');
console.log('--------BNB资产--------:' + balanceFromWei)
使用web3并查询BNB合约币USDT资产
// 实例化代币合约
const tokenContract = new web3.eth.Contract(erc20Abi, contractAddress);
// 查询代币余额
tokenContract.methods.balanceOf(address).call()
.then(balanceNum => {
if (balanceNum / 100000000000000000 > that.userInfo.tokenNum) {
that.userInfo.tokenNum = balanceNum / 100000000000000000;
console.log(that.userInfo.tokenNum)
uni.setStorageSync("userInfo", that.userInfo);
}
})
.catch(error => {
console.error('Error querying token balance:', error);
})
解决办法2: 重写Web3的HttpProvider重写node_node_modules 里面的_prepareRequest函数
如下目录
同解决办法1重写此函数