admin管理员组文章数量:1025244
When trying to run the RPC mands for the methods we get, I can't seem to figure out the issue. It was working on local but not on the live linux server.
TypeError: Cannot read property 'method' of undefined at C:\ssc-exchange-tranactions\app.js:23:13 at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at 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 next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\index.js:275:10) at jsonParser (C:\ssc-exchange-tranactions\node_modules\body-parser\lib\types\json.js:119:7) at 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('');
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 mand', 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: ''+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);
});
When trying to run the RPC mands for the methods we get, I can't seem to figure out the issue. It was working on local but not on the live linux server.
TypeError: Cannot read property 'method' of undefined at C:\ssc-exchange-tranactions\app.js:23:13 at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at 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 next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\index.js:275:10) at jsonParser (C:\ssc-exchange-tranactions\node_modules\body-parser\lib\types\json.js:119:7) at 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.');
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 mand', 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./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);
});
Share
Improve this question
edited Feb 22, 2019 at 18:35
Just a Tester
asked Feb 19, 2019 at 21:46
Just a TesterJust a Tester
111 gold badge1 silver badge4 bronze badges
5
-
What do you expect
body
(or ratherreq.body.curl
) to contain? – user5734311 Commented Feb 19, 2019 at 22:03 -
Ok, well you can't call
JSON.parse()
on that without first getting rid of the stuff that isn't JSON. – user5734311 Commented Feb 20, 2019 at 6:17 - @iBug rolled back. – Alex McMillan Commented Feb 22, 2019 at 1:20
- @AlexMcMillan Thanks. Did you know that ment is automated? :P – iBug Commented Feb 22, 2019 at 1:57
- @iBug no I didn't - but damn that's choice! Well done :) – Alex McMillan Commented Feb 22, 2019 at 2:15
1 Answer
Reset to default 2Your code breaks in the case of an error inside your first try/catch block, which is a semantic error by your side.
try
{
var body=JSON.parse(req.body.curl);
}
catch(err)
{
res.send({msg: 'invalid mand', error: err});
}
1. Variable hoisting in JS
Check the topic of variable hoising in js: https://developer.mozilla/en-US/docs/Glossary/Hoisting
In short, based on your example, this means that JS piler will create a variable called body inside your post function at the very top of the function, which has the initial value of undefined. This happens because you used the var keyword for it, in contrast to const/let.
Only in the case of JSON.parse()
working properly, the value of the body variable will be set. In case of this failing (which happens to you as it seems) or getting an error, body will remain undefined permanently, meaning you cannot access its properties such as method, as it is not an object.
Solutions depend on what you want to achieve here:
- You can put the rest of the code inside try/catch aswell
- You can add an additional check for body aswell
- You could refactor the code a bit to be more readable (which is always subjective of course and depends on the coding style)
An example for refactoring here:
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 mand', error: err });
}
});
If you want to avoid splitting into several functions, you could do something like
app.post('/', function(req, res) {
try {
const body = JSON.parse(req.body.curl);
// Your current else
if(!body.method) {
...code
return; // Will break the execution after this
}
...your normal if/else here with simplified checks now
} catch (err) {
res.send({ msg: 'invalid mand', error: err });
}
});
Considering that everything is wrapped inside try/catch no need to specifically check for body being undefined here.
When trying to run the RPC mands for the methods we get, I can't seem to figure out the issue. It was working on local but not on the live linux server.
TypeError: Cannot read property 'method' of undefined at C:\ssc-exchange-tranactions\app.js:23:13 at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at 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 next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\index.js:275:10) at jsonParser (C:\ssc-exchange-tranactions\node_modules\body-parser\lib\types\json.js:119:7) at 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('');
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 mand', 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: ''+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);
});
When trying to run the RPC mands for the methods we get, I can't seem to figure out the issue. It was working on local but not on the live linux server.
TypeError: Cannot read property 'method' of undefined at C:\ssc-exchange-tranactions\app.js:23:13 at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\ssc-exchange-tranactions\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\ssc-exchange-tranactions\node_modules\express\lib\router\layer.js:95:5) at 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 next (C:\ssc-exchange-tranactions\node_modules\express\lib\router\index.js:275:10) at jsonParser (C:\ssc-exchange-tranactions\node_modules\body-parser\lib\types\json.js:119:7) at 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.');
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 mand', 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./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);
});
Share
Improve this question
edited Feb 22, 2019 at 18:35
Just a Tester
asked Feb 19, 2019 at 21:46
Just a TesterJust a Tester
111 gold badge1 silver badge4 bronze badges
5
-
What do you expect
body
(or ratherreq.body.curl
) to contain? – user5734311 Commented Feb 19, 2019 at 22:03 -
Ok, well you can't call
JSON.parse()
on that without first getting rid of the stuff that isn't JSON. – user5734311 Commented Feb 20, 2019 at 6:17 - @iBug rolled back. – Alex McMillan Commented Feb 22, 2019 at 1:20
- @AlexMcMillan Thanks. Did you know that ment is automated? :P – iBug Commented Feb 22, 2019 at 1:57
- @iBug no I didn't - but damn that's choice! Well done :) – Alex McMillan Commented Feb 22, 2019 at 2:15
1 Answer
Reset to default 2Your code breaks in the case of an error inside your first try/catch block, which is a semantic error by your side.
try
{
var body=JSON.parse(req.body.curl);
}
catch(err)
{
res.send({msg: 'invalid mand', error: err});
}
1. Variable hoisting in JS
Check the topic of variable hoising in js: https://developer.mozilla/en-US/docs/Glossary/Hoisting
In short, based on your example, this means that JS piler will create a variable called body inside your post function at the very top of the function, which has the initial value of undefined. This happens because you used the var keyword for it, in contrast to const/let.
Only in the case of JSON.parse()
working properly, the value of the body variable will be set. In case of this failing (which happens to you as it seems) or getting an error, body will remain undefined permanently, meaning you cannot access its properties such as method, as it is not an object.
Solutions depend on what you want to achieve here:
- You can put the rest of the code inside try/catch aswell
- You can add an additional check for body aswell
- You could refactor the code a bit to be more readable (which is always subjective of course and depends on the coding style)
An example for refactoring here:
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 mand', error: err });
}
});
If you want to avoid splitting into several functions, you could do something like
app.post('/', function(req, res) {
try {
const body = JSON.parse(req.body.curl);
// Your current else
if(!body.method) {
...code
return; // Will break the execution after this
}
...your normal if/else here with simplified checks now
} catch (err) {
res.send({ msg: 'invalid mand', error: err });
}
});
Considering that everything is wrapped inside try/catch no need to specifically check for body being undefined here.
本文标签: javascriptTypeError Cannot read property 39method39 of undefinedStack Overflow
版权声明:本文标题:javascript - TypeError: Cannot read property 'method' of undefined - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745617318a2159367.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论