ethereum geth with web3: privateToAccount not defined - ethereum

According to the doc for web3: http://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html
I can use:
web3.eth.accounts.privateToAccount("0x78...");
I have this error:
TypeError: 'privateToAccount' is not a function
at <anonymous>:1:1
web3.eth.accounts is defined:
> web3.eth.accounts
["0x78...", "0xf3..."]
My question: why the function 'privateToAccount' is not defined ?
Also the result of web3.eth.accounts are private or public keys ?

Ok, I just ran into the same issue and was able to reproduce this.
After some digging I noticed the linked docs are for version 1.0 which is an unreleased future version and uncompleted milestone.
Check your web3.version:
> web3.version
{ api: '0.18.4',
node: [Getter],
getNode: { [Function: get] request: [Function: bound ] },
network: [Getter],
getNetwork: { [Function: get] request: [Function: bound ] },
ethereum: [Getter],
getEthereum: { [Function: get] request: [Function: bound ] },
whisper: [Getter],
getWhisper: { [Function: get] request: [Function: bound ] } }
You will probably get 0.18.x which does not support any eth.accounts sub-functions:
> web3.eth.accounts
web3.eth.accounts

Related

Opensea Api returns Asset does not exist when creating an offer

Hi I use the opensea api to create an offer but all it returns is a 400 Error with the message "Asset does not exist". Even though I use the same API before to retrieve the asset. I use the seaport SDK to create the signature and it all works fine
const { executeAllActions } = await seaport.createOrder(
{
offer: [
{
amount: basePrice.toString(),
token: WETH,
}
],
consideration: [item, ...considerationFeeItems],
endTime: endTime.toString(),
zone: DEFAULT_ZONE_BY_NETWORK[opensea.Network.Main],
restrictedByZone: true,
allowPartialFills: false,
conduitKey: CROSS_CHAIN_DEFAULT_CONDUIT_KEY,
counter: 0
},
ourAddress
);
const order = await executeAllActions();
But as soon as I send it to that endpoint https://docs.opensea.io/v2.0/reference/create-an-offer
it gives me back an error.
The order object returned from executeAllActions looks like following:
{
parameters: {
offerer: '0x...',
zone: '0x004c00500000ad104d7dbd00e3ae0a5c00560c00',
zoneHash: '0x3000000000000000000000000000000000000000000000000000000000000000',
startTime: '1660557986',
endTime: '1660644385',
orderType: 2,
offer: [ [Object] ],
consideration: [ [Object], [Object], [Object] ],
totalOriginalConsiderationItems: 3,
salt: '0xc532bab0fd9ae9529b4d8cfc9fc2f02e',
conduitKey: '0x0000007b02230091a7ed01230072f7006a004d60a8d4e71d599b8104250f0000',
counter: 0
},
signature: '0x....'
}
What is going wrong?

Nodejs with sequelize couldn't create table in mysql workbench after starting the server

I started to learn how to build Rest API using Nodejs,Expressjs,Sequelize and MySQL using Mysqlworkbench.
My Problem: After I start the server, the table is not created by Sequelize and no table in Mysqlworkbench also. Just this message appeared below... Thanks for any guide or help in advance:-
Sequelize {
options:
{ dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone: '+00:00',
logging: [Function: bound consoleCall],
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: { max: 5, match: [Array] },
transactionType: 'DEFERRED',
isolationLevel: null,
databaseVersion: 0,
typeValidation: false,
benchmark: false,
operatorsAliases: false },
config:
{ database: 'node',
username: 'root',
password: '1234567890',
host: 'localhost',
port: 3306,
pool: {},
protocol: 'tcp',
native: false,
ssl: undefined,
replication: false,
dialectModulePath: null,
keepDefaultTimezone: undefined,
dialectOptions: undefined },
dialect:
MysqlDialect {
sequelize: [Circular],
connectionManager:
ConnectionManager {
sequelize: [Circular],
config: [Object],
dialect: [Circular],
versionPromise: null,
dialectName: 'mysql',
pool: [Object],
lib: [Object] },
QueryGenerator:
{ dialect: 'mysql',
OperatorMap: [Object],
createSchema: [Function: createSchema],
showSchemasQuery: [Function: showSchemasQuery],
versionQuery: [Function: versionQuery],
createTableQuery: [Function: createTableQuery],
showTablesQuery: [Function: showTablesQuery],
addColumnQuery: [Function: addColumnQuery],
removeColumnQuery: [Function: removeColumnQuery],
changeColumnQuery: [Function: changeColumnQuery],
renameColumnQuery: [Function: renameColumnQuery],
handleSequelizeMethod: [Function: handleSequelizeMethod],
_toJSONValue: [Function: _toJSONValue],
upsertQuery: [Function: upsertQuery],
deleteQuery: [Function: deleteQuery],
showIndexesQuery: [Function: showIndexesQuery],
showConstraintsQuery: [Function: showConstraintsQuery],
removeIndexQuery: [Function: removeIndexQuery],
attributeToSQL: [Function: attributeToSQL],
attributesToSQL: [Function: attributesToSQL],
quoteIdentifier: [Function: quoteIdentifier],
_checkValidJsonStatement: [Function: _checkValidJsonStatement],
jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
_getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
getForeignKeysQuery: [Function: getForeignKeysQuery],
getForeignKeyQuery: [Function: getForeignKeyQuery],
dropForeignKeyQuery: [Function: dropForeignKeyQuery],
_templateSettings: [Object],
options: [Object],
extractTableDetails: [Function: extractTableDetails],
addSchema: [Function: addSchema],
dropSchema: [Function: dropSchema],
describeTableQuery: [Function: describeTableQuery],
dropTableQuery: [Function: dropTableQuery],
renameTableQuery: [Function: renameTableQuery],
insertQuery: [Function: insertQuery],
bulkInsertQuery: [Function: bulkInsertQuery],
updateQuery: [Function: updateQuery],
arithmeticQuery: [Function: arithmeticQuery],
nameIndexes: [Function: nameIndexes],
addIndexQuery: [Function: addIndexQuery],
addConstraintQuery: [Function: addConstraintQuery],
getConstraintSnippet: [Function: getConstraintSnippet],
removeConstraintQuery: [Function: removeConstraintQuery],
quoteTable: [Function: quoteTable],
quote: [Function: quote],
quoteIdentifiers: [Function: quoteIdentifiers],
escape: [Function: escape],
selectQuery: [Function: selectQuery],
escapeAttributes: [Function: escapeAttributes],
generateInclude: [Function: generateInclude],
generateJoin: [Function: generateJoin],
generateThroughJoin: [Function: generateThroughJoin],
_generateSubQueryFilter: [Function: _generateSubQueryFilter],
_getRequiredClosure: [Function: _getRequiredClosure],
getQueryOrders: [Function: getQueryOrders],
selectFromTableFragment: [Function: selectFromTableFragment],
setAutocommitQuery: [Function: setAutocommitQuery],
setIsolationLevelQuery: [Function: setIsolationLevelQuery],
generateTransactionId: [Function: generateTransactionId],
startTransactionQuery: [Function: startTransactionQuery],
deferConstraintsQuery: [Function: deferConstraintsQuery],
setConstraintQuery: [Function: setConstraintQuery],
setDeferredQuery: [Function: setDeferredQuery],
setImmediateQuery: [Function: setImmediateQuery],
commitTransactionQuery: [Function: commitTransactionQuery],
rollbackTransactionQuery: [Function: rollbackTransactionQuery],
addLimitAndOffset: [Function: addLimitAndOffset],
whereQuery: [Function: whereQuery],
whereItemsQuery: [Function: whereItemsQuery],
OperatorsAliasMap: false,
setOperatorsAliases: [Function: setOperatorsAliases],
whereItemQuery: [Function: whereItemQuery],
_findField: [Function: _findField],
_replaceAliases: [Function: _replaceAliases],
_whereGroupBind: [Function: _whereGroupBind],
_whereBind: [Function: _whereBind],
_whereJSON: [Function: _whereJSON],
_traverseJSON: [Function: _traverseJSON],
_castKey: [Function: _castKey],
_getJsonCast: [Function: _getJsonCast],
_joinKeyValue: [Function: _joinKeyValue],
_getSafeKey: [Function: _getSafeKey],
_prefixKey: [Function: _prefixKey],
_whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
getWhereConditions: [Function: getWhereConditions],
parseConditionObject: [Function: parseConditionObject],
isIdentifierQuoted: [Function: isIdentifierQuoted],
booleanValue: [Function: booleanValue],
_dialect: [Circular],
sequelize: [Circular],
typeValidation: undefined } },
queryInterface:
QueryInterface {
sequelize: [Circular],
QueryGenerator:
{ dialect: 'mysql',
OperatorMap: [Object],
createSchema: [Function: createSchema],
showSchemasQuery: [Function: showSchemasQuery],
versionQuery: [Function: versionQuery],
createTableQuery: [Function: createTableQuery],
showTablesQuery: [Function: showTablesQuery],
addColumnQuery: [Function: addColumnQuery],
removeColumnQuery: [Function: removeColumnQuery],
changeColumnQuery: [Function: changeColumnQuery],
renameColumnQuery: [Function: renameColumnQuery],
handleSequelizeMethod: [Function: handleSequelizeMethod],
_toJSONValue: [Function: _toJSONValue],
upsertQuery: [Function: upsertQuery],
deleteQuery: [Function: deleteQuery],
showIndexesQuery: [Function: showIndexesQuery],
showConstraintsQuery: [Function: showConstraintsQuery],
removeIndexQuery: [Function: removeIndexQuery],
attributeToSQL: [Function: attributeToSQL],
attributesToSQL: [Function: attributesToSQL],
quoteIdentifier: [Function: quoteIdentifier],
_checkValidJsonStatement: [Function: _checkValidJsonStatement],
jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
_getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
getForeignKeysQuery: [Function: getForeignKeysQuery],
getForeignKeyQuery: [Function: getForeignKeyQuery],
dropForeignKeyQuery: [Function: dropForeignKeyQuery],
_templateSettings: [Object],
options: [Object],
extractTableDetails: [Function: extractTableDetails],
addSchema: [Function: addSchema],
dropSchema: [Function: dropSchema],
describeTableQuery: [Function: describeTableQuery],
dropTableQuery: [Function: dropTableQuery],
renameTableQuery: [Function: renameTableQuery],
insertQuery: [Function: insertQuery],
bulkInsertQuery: [Function: bulkInsertQuery],
updateQuery: [Function: updateQuery],
arithmeticQuery: [Function: arithmeticQuery],
nameIndexes: [Function: nameIndexes],
addIndexQuery: [Function: addIndexQuery],
addConstraintQuery: [Function: addConstraintQuery],
getConstraintSnippet: [Function: getConstraintSnippet],
removeConstraintQuery: [Function: removeConstraintQuery],
quoteTable: [Function: quoteTable],
quote: [Function: quote],
quoteIdentifiers: [Function: quoteIdentifiers],
escape: [Function: escape],
selectQuery: [Function: selectQuery],
escapeAttributes: [Function: escapeAttributes],
generateInclude: [Function: generateInclude],
generateJoin: [Function: generateJoin],
generateThroughJoin: [Function: generateThroughJoin],
_generateSubQueryFilter: [Function: _generateSubQueryFilter],
_getRequiredClosure: [Function: _getRequiredClosure],
getQueryOrders: [Function: getQueryOrders],
selectFromTableFragment: [Function: selectFromTableFragment],
setAutocommitQuery: [Function: setAutocommitQuery],
setIsolationLevelQuery: [Function: setIsolationLevelQuery],
generateTransactionId: [Function: generateTransactionId],
startTransactionQuery: [Function: startTransactionQuery],
deferConstraintsQuery: [Function: deferConstraintsQuery],
setConstraintQuery: [Function: setConstraintQuery],
setDeferredQuery: [Function: setDeferredQuery],
setImmediateQuery: [Function: setImmediateQuery],
commitTransactionQuery: [Function: commitTransactionQuery],
rollbackTransactionQuery: [Function: rollbackTransactionQuery],
addLimitAndOffset: [Function: addLimitAndOffset],
whereQuery: [Function: whereQuery],
whereItemsQuery: [Function: whereItemsQuery],
OperatorsAliasMap: false,
setOperatorsAliases: [Function: setOperatorsAliases],
whereItemQuery: [Function: whereItemQuery],
_findField: [Function: _findField],
_replaceAliases: [Function: _replaceAliases],
_whereGroupBind: [Function: _whereGroupBind],
_whereBind: [Function: _whereBind],
_whereJSON: [Function: _whereJSON],
_traverseJSON: [Function: _traverseJSON],
_castKey: [Function: _castKey],
_getJsonCast: [Function: _getJsonCast],
_joinKeyValue: [Function: _joinKeyValue],
_getSafeKey: [Function: _getSafeKey],
_prefixKey: [Function: _prefixKey],
_whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
getWhereConditions: [Function: getWhereConditions],
parseConditionObject: [Function: parseConditionObject],
isIdentifierQuoted: [Function: isIdentifierQuoted],
booleanValue: [Function: booleanValue],
_dialect: [Object],
sequelize: [Circular],
typeValidation: undefined } },
models: {},
modelManager: ModelManager { models: [], sequelize: [Circular] },
connectionManager:
ConnectionManager {
sequelize: [Circular],
config:
{ database: 'node',
username: 'root',
password: '1234567890',
host: 'localhost',
port: undefined,
pool: [Object],
protocol: 'tcp',
native: false,
ssl: undefined,
replication: false,
dialectModulePath: null,
keepDefaultTimezone: undefined,
dialectOptions: undefined },
dialect:
MysqlDialect {
sequelize: [Circular],
connectionManager: [Circular],
QueryGenerator: [Object] },
versionPromise: null,
dialectName: 'mysql',
pool:
Pool {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
_config: [Object],
_Promise: [Object],
_factory: [Object],
_draining: false,
_started: false,
_waitingClientsQueue: [Object],
_factoryCreateOperations: Set {},
_factoryDestroyOperations: Set {},
_availableObjects: [Object],
_testOnBorrowResources: Set {},
_testOnReturnResources: Set {},
_validationOperations: Set {},
_allObjects: Set {},
_resourceLoans: Map {},
_evictionIterator: [Object],
_evictor: DefaultEvictor {},
_scheduledEviction: null },
lib:
{ createConnection: [Function],
connect: [Function],
Connection: [Function: Connection],
createPool: [Function],
createPoolCluster: [Function],
createQuery: [Function: createQuery],
Pool: [Function: Pool],
createServer: [Function],
PoolConnection: [Object],
escape: [Function: escape],
escapeId: [Function: escapeId],
format: [Function: format],
raw: [Function: raw],
createConnectionPromise: [Getter],
createPoolPromise: [Getter],
createPoolClusterPromise: [Getter],
Types: [Getter],
Charsets: [Getter],
CharsetToEncoding: [Getter],
setMaxParserCache: [Function],
clearParserCache: [Function] } },
importCache: {},
test:
{ _trackRunningQueries: false,
_runningQueries: 0,
trackRunningQueries: [Function: trackRunningQueries],
verifyNoRunningQueries: [Function: verifyNoRunningQueries] } }
model product.js
const Sequelize = require('sequelize');
const sequelize = require('./dbconfig');
const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = Product;
App.js
const express = require('express');
const feedroutes = require('./routes/feed');
const bodyParser = require('body-parser');
const sequelize = require('./dbconfig');
const app = express()
app.use(bodyParser.json());//application/json
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/feed',feedroutes);
sequelize.sync().then(reslut => {
console.log(reslut);
app.listen(8080);
})
.catch(error => {
console.log(error);
});
dbconfig.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node','root','1234567890', {
operatorsAliases: false ,
dialect: 'mysql',
host:'localhost'
});
module.exports = sequelize;
since your product model is in a separate file you are required to import it using the import method available on sequelize instance as follows
model product.js
module.exports = function(sequelize, Sequelize) {
const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = Product;
};
dbconfig.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node','root','1234567890', {
operatorsAliases: false ,
dialect: 'mysql',
host:'localhost'
});
sequelize.import('path/to/product/model');
module.exports = sequelize;
Reference sequelize import
Project Demo
Your route middleware always should be located after sequelize.sync() (not only sequelize.sync() but all configs related to your application)
After route response with res.render() or res.send() etc, next() will not be invoked.
Whereas You can locate your error handling middleware after the route middlewares.

Validate ABI JSon (Ethereum)

i've a problem with the following Json :
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function'
}, {
constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function'
}, {
anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event'
},
set: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
uint256: [Circular]
},
get: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
'': [Circular]
},
allEvents: [Function: bound],
ItBlinks: {
[Function: bound] uint256: [Function: bound]
}
}
This JSon is the ABI and this should be add to my contract into my wallet (Ethereum Wallet) to send information (in this case, made a blink event on my raspberry PI)
When I add these line into my contract in my ethereum wallet, it tell me my Json is not correct.
I've try to validate, but it give me an error, and i cannot solve it. (I'm a beginner in JSon)
Somebody can help me to validate the get / set method? to be a valid JSon format?
This is the full return with coinbase (the address and coinbase is modified) :
coinbase : 0x20408a19c567a475545947600a95130f24f7C123
{ _eth:
Eth {
_requestManager: { provider: [Object], polls: {}, timeout: null },
getBalance: { [Function] request: [Function: bound ], call: 'eth_getBalance' },
getStorageAt: { [Function] request: [Function: bound ], call: 'eth_getStorageAt' },
getCode: { [Function] request: [Function: bound ], call: 'eth_getCode' },
getBlock: { [Function] request: [Function: bound ], call: [Function] },
getUncle: { [Function] request: [Function: bound ], call: [Function] },
getCompilers: { [Function] request: [Function: bound ], call: 'eth_getCompilers' },
getBlockTransactionCount: { [Function] request: [Function: bound ], call: [Function] },
getBlockUncleCount: { [Function] request: [Function: bound ], call: [Function] },
getTransaction:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionByHash' },
getTransactionFromBlock: { [Function] request: [Function: bound ], call: [Function] },
getTransactionReceipt:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionReceipt' },
getTransactionCount: { [Function] request: [Function: bound ], call: 'eth_getTransactionCount' },
call: { [Function] request: [Function: bound ], call: 'eth_call' },
estimateGas: { [Function] request: [Function: bound ], call: 'eth_estimateGas' },
sendRawTransaction: { [Function] request: [Function: bound ], call: 'eth_sendRawTransaction' },
signTransaction: { [Function] request: [Function: bound ], call: 'eth_signTransaction' },
sendTransaction: { [Function] request: [Function: bound ], call: 'eth_sendTransaction' },
sign: { [Function] request: [Function: bound ], call: 'eth_sign' },
compile: { solidity: [Object], lll: [Object], serpent: [Object] },
submitWork: { [Function] request: [Function: bound ], call: 'eth_submitWork' },
getWork: { [Function] request: [Function: bound ], call: 'eth_getWork' },
coinbase: [Getter],
getCoinbase: { [Function] request: [Function: bound ] },
mining: [Getter],
getMining: { [Function] request: [Function: bound ] },
hashrate: [Getter],
getHashrate: { [Function] request: [Function: bound ] },
syncing: [Getter],
getSyncing: { [Function] request: [Function: bound ] },
gasPrice: [Getter],
getGasPrice: { [Function] request: [Function: bound ] },
accounts: [Getter],
getAccounts: { [Function] request: [Function: bound ] },
blockNumber: [Getter],
getBlockNumber: { [Function] request: [Function: bound ] },
protocolVersion: [Getter],
getProtocolVersion: { [Function] request: [Function: bound ] },
iban:
{ [Function]
fromAddress: [Function],
fromBban: [Function],
createIndirect: [Function],
isValid: [Function] },
sendIBANTransaction: [Function: bound ] },
transactionHash: null,
address: '0x9535eb707582edb3317dfdcdb365ce4186500C123',
abi:
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ],
set:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
uint256: [Circular] },
get:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
'': [Circular] },
allEvents: [Function: bound ],
ItBlinks: { [Function: bound ] uint256: [Function: bound ] }
}
You do not have valid JSON. JSON has key/value pairs with keys being strings delimited by double quotes. Details of JSON can be found here
From the Ethereum documentation this is an example of JSON in the ABI:
[{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}]
Details of the ethereum contract ABI can be found here
What you were showing is a payload from coinbase it contains lots of information regarding your request, the smart-contracts ABI is one of them.
In reality it is only
abi:[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ]
you can access the abi by doing this
coinbase[0x20408a19c567a475545947600a95130f24f7C123].abi
i don't know your exact use case but i suggest you read about smart contracts abis here
I did have the same issue.
The problem is this [Object] inside your JSON
You probably get the ABI from console.log object.
You have to convert this JSON object to a string, and then console.log it and grab the output which will be a valid JSON.

Alexa JSON Request doesn't match Intent Schema

I am hosting an application server with Express (Versions: "body-parser": 1.14.2", "express": "^4.13.3", "parse-http-header": "^1.0.0", "x509": "^0.2.3")
Node v5.4.1 NPM v3.3.12
I have successfully tested the SSL connection between Alexa and my local App server, however, when I parse the Request from Alexa it doesn't match my Intent Schema or the generated Service Request under the Service Simulator - Test.
Code:
const fs = require('fs'); //File System, for loading certifications and keys
var http = require('http');
var https = require('https'); //Https server module
var bodyParser = require('body-parser');
var parseHttpHeader = require('parse-http-header');
/***************** Credentials **********************/
const privateKey = fs.readFileSync('keys/private-key.pem'); //Private Key for validation (server uses only)
const certificate = fs.readFileSync('certs/certificate.pem'); //Certificate, to provide to connecting host.
const options = {
key: privateKey,
cert: certificate
};
/******** Instantiate the Express server *************/
var express = require('express');
var app = express(); //Instantiate express server
//Express configuration
app.set('title', 'mySkillJS');
app.set('json spaces', 2);
//Route all requests from app
app.all('/*', function(request, response){
//Handle request
var bucket = request;
console.log('\n \n \n &&&&&& \n \n \n');
var joptions = {
type: 'application/json'
}
var bodyParsed = app.use(bodyParser.json(joptions));
console.log(bodyParsed);
var headParsed = parseHttpHeader(bucket.headers['content-type'])[0];
console.log(headParsed);
});
//Ceate Server with SSL credentials
var httpsServer = https.createServer(options, app).listen(8000);//createServer(options, fx(req, res))
Intent Schema:
{
"intents": [
{
"intent": "HelloWorldIntent"
},
{
"intent": "AMAZON.HelpIntent"
}
]
}
generated Service Request:
{
"session": {
"sessionId": "SessionId.efb0235c-8201-4877-832e-58671b42c9b5",
"application": {
"applicationId": "amzn1.echo-sdk-ams.app.9eb766d1-f6a6-4ac7-9801-ce1478782b98"
},
"user": {
"userId": "amzn1.echo-sdk-account.AHUTLGA6FMHPERGIUSQTTXG2RLOABOBTGSGN4LXBEWYK2XDLDRXU2"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.734c7e4a-ec2c-4bdf-b2bc-37757796e670",
"timestamp": "2016-01-22T04:10:18Z",
"intent": {
"name": "HelloWorldIntent",
"slots": {}
}
}
}
Request from Alexa handled by my app server:
&&&&&&
{ [Function]
domain: undefined,
_events: { mount: [Function: onmount] },
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: use],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: listen],
request: IncomingMessage { app: [Circular] },
response: ServerResponse { app: [Circular] },
cache: {},
engines: {},
settings:
{ 'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: wetag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: '/home/dev/Alexa/alexa-js-mod/samples/helloWorld/src/views',
'jsonp callback name': 'callback',
title: 'mySkillJS',
'json spaces': 2 },
_eventsCount: 1,
locals:
{ settings:
{ 'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: wetag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: '/home/dev/Alexa/alexa-js-mod/samples/helloWorld/src/views',
'jsonp callback name': 'callback',
title: 'mySkillJS',
'json spaces': 2 } },
mountpath: '/',
_router:
{ [Function: router]
params: {},
_params: [],
caseSensitive: false,
mergeParams: undefined,
strict: false,
stack: [ [Object], [Object], [Object], [Object] ] } }
application/json
I am not sure what I am doing wrong. I thought that Request would hold something similar to either my Intent Schema or the generated Service Request. Why don't I see Intent Schema or my generated Service Request in the JSON Request I receive from Alexa?
So this problem arose because of inexperience with the express module.
I thought bodyParsed would hold a value returned from: app.use(bodyParser.json());
when you use app.use(bodyParser.json());
It actually stores it in the body property of the Request.
So:
app.use(bodyParser.json(joptions));//causes request.body to populate with the JSON data
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded requires multer
app.all('/*', function(request, response){
//Handle request
var bucket = request;
console.log('\n \n \n &&&&&& \n \n \n');
var joptions = {
type: 'application/json'
}
console.log(request.body));
var headParsed = parseHttpHeader(bucket.headers['content-type'])[0];
console.log(headParsed);
});
Not sure if this forces all requests to be parsed as application/json. Maybe moving the bodyparser inside the app.all() will cause it to only parse when using that route?

AWS requests using nodeJS

I have a webpage which has a button. On clicking of button it calls a nodejs method which returns the status of my EC2 instances on my AWS account. To host webpage I have used nodeJS. For connection between my aws account and webpage I have used AWS NodeJS sdk.
The response I am getting (statuses of EC2) is in json format.Following is the response-
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
C:\NodeTest>node DescribeInstances.js
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
This response is coming in command prompt. Now I want this response to be displayed on a webpage. How should I do it. Or how can I use response of ec2 instance to take further action like if one ec2 is running the close it. Any help would be appreciated. I am new to NodeJs. Thanks in Advance.
What you have posted here is "backend code", or code that runs behind your server that your users will never see.
You need to add "front end code" to this system. Android apps, windows applications, and websites are all examples of "front ends".
Common nodejs libraries used to provide a web front end are:
Express
Koa
Native HTTP module
For the rest of this answer, I'll be assuming you choose express because it's the easiest for a beginner to understand, in my opinion.
A simple webserver
The simplest example of adding a webpage would look like this.
var express = require( 'express' )
var app = express()
var myAwsFetcher = require( './aws-fetcher' )
app.get( '/', function( req, res ){
myAwsFetcher( function( err, data ){
res.send( data )
})
})
app.listen( 8888, function(){
console.log( 'App is listening on localhost:8888' )
})
This way, when you run node index.js and go to http://localhost:8888, you should see in your browser:
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
To display the response you can define:
<body>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>
</body>
and replace: console.log(response);
whith: document.getElementById('textarea').innerHTML = response;