So I have this problem when i used "window.web3.currentProvider" on my controller in express js, which i got an error say "window is undefined". And i know the "window" is not to work on server side.
Here is my code : (to post upload file), that works just fine, but i need my Metamask to popup so it can confirm the transaction and im still using TESTRPC. So is there any solution for me? Thank you~
exports.postUploadFile = (req, res, next) => {
var ethereumURI = req.body.ethereumURI;
var abi = JSON.parse(req.body.abi);
var contractAddress = req.body.contractAddress;
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(ethereumURI));
//define default account[0]
const address = web3.eth.accounts[0];
const fileTitle = req.body.fileTitle;
const description = req.body.description;
const file = req.file;
const fileUrl = file.path;
const fileName = file.filename;
const submitAt = moment(new Date(Date.now())).format('DD-MM-YYYY, HH:mm:ss');
const newReportFile = fs.readFileSync(req.file.path);
const encodingBase64 = newReportFile.toString('base64');
const encodingMD5 = crypto.createHash('md5').update(newReportFile).digest('HEX');
if (!web3.isConnected()) {
throw new Error('unable to connect to ethereum node at ' + ethereumURI);
} else {
console.log('connected to ethereum node at ' + ethereumURI);
let accounts = web3.eth.accounts[0];
console.log('account : ' + accounts);
}
var DFRVerificationContract = web3.eth.contract(abi);
var Report = DFRVerificationContract.at(contractAddress);
console.log('Report has been sent!');
const bapFiles = new BapFiles({
fileName: fileName,
submitAt: submitAt,
fileTitle: fileTitle,
description: description,
fileUrl: fileUrl,
userId: req.user
});
bapFiles.reportFile.data = encodingBase64;
bapFiles.reportFile.contentType = req.file.mimetype;
bapFiles.reportFileHash = encodingMD5;
if (req.session.isLoggedIn) {
bapFiles.save().then(result => {
console.log(result);
var id = result._id;
console.log('ID:', id);
var fileReport = {
filePath: fileUrl,
fileName: fileName,
fileHash: encodingMD5,
description: description,
createdAt: submitAt
};
var reportObject = JSON.stringify(fileReport);
var reportWithoutQuotes = reportObject.toString().replace(/"/g, "");
var idObject = JSON.stringify(id);
var IDWithoutQuotes = idObject.toString().replace(/"/g, "");
console.log(fileTitle);
console.log(reportWithoutQuotes);
console.log('address: ', address);
console.log(Report);
Report.uploadReport(IDWithoutQuotes, fileTitle, reportWithoutQuotes, address, {
from: address,
gas: '4700000'
});
console.log('Success Upload File!');
res.redirect('/user/list-upload');
}).catch(err => {
console.log(err);
});
} else {
console.log('Fail to Upload File');
console.log('User not Logged In. Please Login first!');
return res.redirect('/');
}
}