TypeError:无法读取undefined的属性'method'

问题描述 投票:0回答:1

当我们尝试为我们获得的方法运行RPC命令时,我似乎无法弄清楚问题。它在本地工作但不在实时Linux服务器上工作。

TypeError:无法在C:\ ssc-exchange-tranactions \ app.js:23:13在Layer.handle中读取未定义的属性'method'[as handle_request](C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ layer.js:95:5)at Route.dispatch(C:\ ssc-exchange)下一步(C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ route.js:137:13) -tranactions \ node_modules \ express \ lib \ router \ route.js:112:3)在Layer.handle [as handle_request](C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ layer.js:95) :5)在C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ index.js:281:22 at Function.process_params(C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ index.js:335:12)at jsonParser(C:\ ssc-exchange-tranactions \ node_modules \) body-parser \ lib \ types \ json.js:119:7)在Layer.handle [as handle_request](C:\ ssc-exchange-tranactions \ node_modules \ express \ lib \ router \ layer.js:95:5)

const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const port = 5000;
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const dsteem = require('dsteem');
const client = new dsteem.Client('https://api.site.com');
app.set('trust proxy', true);
app.disable('x-powered-by');


app.post('/', function(req,res){
    try
    {
    var body=JSON.parse(req.body.curl);
    }
    catch(err)
    {
     res.send({msg: 'invalid command', error: err});
    }
    if(body.method !=undefined && body.method == "POST")
    {
    let options = {
      url:body.url,
      method:body.method,
      headers:body.headers,
      body: JSON.stringify(body.body)
    };
    request(options, (error, response, body) => {
      if (error) {
        console.error("An error has occurred: ", error);
        res.send(error);
      }
      else {
        let responseData = JSON.parse(body);
        res.send(responseData);
      }
    });
  }
  ///Ends if
  else if(body.method != undefined && body.method == "GET")
  {
    let options = {
    //   url: body.url+'?account='+body.body.params.account+'&limit='+body.body.params.limit+
    //   '&offset='+body.body.params.offset+'&&symbol='+body.body.params.symbol,
         url: 'https://api.site.com/accounts/history'+body.symbol,
         method: "GET",
         headers: {"Content-type": "application/json"},
    };
    request(options, (error, response, body) => {
      if (error) {
        console.error("An error has occurred: ", error);
        res.send(error);
      }
      else {
         var withdraw = [], deposit = [];
         body= JSON.parse(body);
         body.forEach(el => {
           if(el.from == "account"){
            delete el.block;
            delete el.symbol;
            delete el.from_type;
            delete el.to_type;
             withdraw.push(el);
           }
           else{
            delete el.block;
            delete el.symbol;
            delete el.from_type;
            delete el.to_type;
            deposit.push(el);
           }

         });
         res.json([{"WITHDRAWS": withdraw},{"DEPOSITS":deposit}]);
      }
    });
  }
  //ends else if
  else
  {
    const active_key = body.wif;
    const key = dsteem.PrivateKey.fromString(active_key);
    const account = "account";
    const my_id= "mainnet";
    const my_data= {"contractName":"tokens", "contractAction":"transfer","contractPayload":{"symbol": "omg",
    "to": body.to,"quantity":body.quantity,"memo": body.memo }};
    client.broadcast.json({
        required_auths: [account],
        required_posting_auths: [],
        id: my_id,
        json: JSON.stringify(my_data),
    }, key).then(
        result => {res.send(result)},
        error => {res.send({msg: 'Something went wrong', error: error})}
    )
  }
  //ends else
  });

app.listen(port, function () {
  console.log("Server listening on port: " + port);
});
javascript node.js rpc
1个回答
0
投票

如果第一个try / catch块中出现错误,您的代码就会中断,这是您身边的语义错误。

try
{
  var body=JSON.parse(req.body.curl);
}
catch(err)
{
   res.send({msg: 'invalid command', error: err});
}

1. JS中的可变吊装

检查js中变量提升的主题:qazxsw poi

简而言之,基于您的示例,这意味着JS编译器将在函数的最顶部在post函数内创建一个名为body的变量,其初始值为undefined。发生这种情况是因为你使用了var关键字,而不是const / let。

只有在https://developer.mozilla.org/en-US/docs/Glossary/Hoisting正常工作的情况下,才会设置body变量的值。如果出现这种情况失败(看起来似乎发生了这种情况)或者出现错误,则正文将永久保持未定义状态,这意味着您无法访问其属性(如方法),因为它不是对象。

解决方案取决于您希望在此实现的目标:

  1. 您可以将其余代码放在try / catch中
  2. 您也可以为身体添加额外的检查
  3. 您可以稍微重构代码以使其更具可读性(当然这总是主观的并且取决于编码风格)

这里重构的一个例子:

JSON.parse()

如果你想避免分成几个函数,你可以做类似的事情

app.post('/', function(req, res) {
  try {
    const body = JSON.parse(req.body.curl);

    switch (body.method) {
      case 'GET':
        this.handleGETRequest();
      case 'POST':
        this.handlePOSTRequest();
      default:
        this.handleDefault();
    }
  } catch (err) {
    res.send({ msg: 'invalid command', error: err });
  }
});

考虑到所有内容都包含在try / catch中,无需在此处专门检查未定义的主体。

© www.soinside.com 2019 - 2024. All rights reserved.