You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行node deploy.js报SyntaxError:JSON第0位意外token u,合约部署无返回地址

问题根因及修复方案

SyntaxError: Unexpected token u in JSON at position 0 错误的核心成因是你传入JSON.parse()方法的参数为undefined,undefined转为字符串时首字符为u,解析器读取第一个字符就触发语法错误。你之前在compile.js中使用的修复逻辑是解决solc编译器入参格式的问题,和当前问题场景完全不同,因此不生效。

你代码中的问题点

你写的部署逻辑存在冗余引入和字段不匹配的问题:

  • 你既从./compile文件引入了interface和bytecode变量,又单独引入了./build/Purchase.json的编译产物
  • 你调用JSON.parse(compiledPurchase.interface)时,大概率你的Purchase.json编译产物中不存在interface字段(多数版本的solc编译输出的ABI对应字段名为abi而非interface),导致compiledPurchase.interface取值为undefined,触发报错。

修复方案(二选一即可)

方案1:直接使用从compile.js引入的变量

把部署相关代码替换为以下内容即可:

const result = await new web3.eth.Contract(
        JSON.parse(interface)
    )
    .deploy({ data: bytecode })
    .send({ gas: "1000000", from: accounts[0] });

方案2:校验Purchase.json的字段后调整代码

在实例化Contract的代码前加一行日志,确认编译产物的实际字段名:

console.log('编译产物内容:', compiledPurchase)

运行代码后查看日志输出的对象结构,如果ABI对应的字段是abi、字节码对应的字段是bytecode,就把部署代码调整为:

const result = await new web3.eth.Contract(
        compiledPurchase.abi // 注意如果字段值已经是对象就不需要再JSON.parse
    )
    .deploy({ data: '0x' + compiledPurchase.bytecode }) // 部分场景需要加0x前缀才可以正常部署
    .send({ gas: "1000000", from: accounts[0] });

补充排查技巧

可以给你的deploy函数加异常捕获,打印完整报错信息方便定位问题:

const deploy = async() => {
  try {
    const accounts = await web3.eth.getAccounts();
    console.log("Attempting to deploy from account", accounts[0]);
    const result = await new web3.eth.Contract(
            JSON.parse(interface)
        )
        .deploy({ data: bytecode })
        .send({ gas: "1000000", from: accounts[0] });
    console.log("Contract deployed to", result.options.address);
  } catch (err) {
    console.error('部署报错完整信息:', err)
  }
};
deploy();

内容的提问来源于stack exchange,提问作者Miguel Pires

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:18:05