从getServerSideProps()-next.js调用solidity约定函数时出现错误响应


import React, { Component } from "react";
import factory from "../ethereum/factory";
import { ethers } from "ethers";
class CampaignIndex extends Component {
render() {
return <div>campaigns{this.props.campaigns}</div>;
}
}
export async function getServerSideProps() {
const campaigns = await factory.getDeployedCampaigns();
await campaigns.wait();
console.log(campaigns);
return { campaigns };
}
export default CampaignIndex;

->工厂是已部署合同的实例
->getDeployedCampaigns((是已部署合约中的一个函数,它返回地址数组
->使用Next.js v12.3.1

当我从getServerSideProps((块调用getDeployedCampaigns((时,它会返回一个错误-错误请求,但如果我从其他地方调用上述函数-除了该块,我会得到预期的结果。我不知道next.js为什么会这样。

getServerSideProps在请求时在服务器端运行。因此,在这种情况下,必须在getServerSideProps函数内实例化智能合约。

export async function getServerSideProps(context) {
const URL = "Provider URL";
let customHttpProvider = new ethers.providers.JsonRpcProvider(URL);
const contract = new ethers.Contract(
<Contract address>,
<ABI>,
customHttpProvider
);
return { props: { data: JSON.stringify(await contract.getDeployedCampaigns()) } 
};

getServerSideProps必须始终返回JSON可序列化数据类型。如果getDeployedCampaigns((返回JSON可序列化数据类型,则无需编写JSON.stringify((

最新更新