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

莱特币测试网发送含tx_hex的原始交易API请求失败求助

嘿,我来帮你排查下这个问题!浏览器手动提交能成但API调用失败,大概率是请求格式或者头部设置不对——毕竟浏览器会自动处理一些默认的请求头和数据格式,而代码里需要明确配置。我帮你分析下两段代码的问题并给出修正方案:

问题1:testnet.litecore.io API调用失败

这个端点要求直接发送原始的十六进制交易字符串作为请求体,并且需要设置正确的Content-Type为纯文本。你之前的代码用了data: test_tx(request库的标准参数应该是body),而且没指定Content-Type,导致服务器无法正确解析请求。

修正后的代码:

request({
  url: 'https://testnet.litecore.io/tx/send',
  method: 'POST',
  body: test_tx, // 直接传入原始tx_hex字符串作为请求体
  headers: {
    'Content-Type': 'text/plain' // 明确告诉服务器这是纯文本格式
  }
}, (error, response, body) => {
  if (error) {
    console.log(error);
  } else {
    console.log(body);
  }
});

问题2:chain.so API调用失败

chain.so的send_tx接口接受**表单格式(x-www-form-urlencoded)**或者JSON格式的请求,但你之前的代码直接把对象作为post参数,request库可能没有正确序列化数据或者设置请求头。

方案1:用表单格式发送

const postdata = { tx_hex: test_tx };
request.post({
  url: 'https://chain.so/api/v2/send_tx/LTCTEST',
  form: postdata, // 使用form参数自动序列化表单数据
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}, (err, httpResponse, body) => {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful! Server responded with:', body);
});

方案2:用JSON格式发送

如果更习惯JSON格式,也可以这样写(request的json选项会自动设置Content-Type并序列化数据):

const postdata = { tx_hex: test_tx };
request.post({
  url: 'https://chain.so/api/v2/send_tx/LTCTEST',
  json: postdata
}, (err, httpResponse, body) => {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful! Server responded with:', body);
});

额外建议

如果还是有问题,可以先用Postman或者curl手动模拟请求,确认请求体和头部设置正确后再对应调整代码,这样能更快定位问题~

内容的提问来源于stack exchange,提问作者Дима Марков

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:46:07