AWS requests using nodeJS - json

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;

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?

NuxtJS - Google Auth: ExpiredAuthSessionError: Both token and refresh token have expired. Your request was aborted

Im using nuxtjs for a while. Before my last update all auth feature run smoothly.
But after I update the nuxt.config.js move axios plugin from plugins array to auth config object the error occurred. I need to put axios in auth config object because I need to access $auth from axios plugin.
Version
"#nuxtjs/auth-next": "5.0.0-1607693598.34d83ea"
"nuxt": "^2.15.2"
Nuxt configuration
Mode:
Universal
Nuxt configuration
auth: {
plugins: [{ src: "~/plugins/axios.js", ssr: true }], // <-- I put this, move from plugins array
strategies: {
local: {
token: {
property: "data.token",
required: true,
type: "",
maxAge: 18000,
},
user: {
property: "data",
autoFetch: true,
},
endpoints: {
login: { url: "/api/main", method: "post" },
logout: { url: "/api/profiles/logout", method: "get" },
user: { url: "/api/profile", method: "get" },
},
},
google: {
responseType: "code",
clientId:"<google client ID>",
codeChallengeMethod: "",
grantType: "authorization_code",
redirectUri: `${baseUrl}/verify-auth`,
},
},
redirect: {
login: "/login",
logout: "/login",
callback: "/login",
home: "/",
},
},
Reproduction
ExpiredAuthSessionError: Both token and refresh token have expired. Your request was aborted.
at a5d2e4e.js:1:4374
Steps to reproduce
After selecting a google account, then redirected to /verify-auth, then the error occurred. After /verify-auth it should go in.
Update google auth config like this:
google: {
responseType: "code",
clientId:"<google client ID>",
codeChallengeMethod: "",
grantType: "authorization_code",
redirectUri: `${baseUrl}/verify-auth`,
token: {
property: "data.token", // <-- based on your API response (endpints.login)
required: true,
type: "",
maxAge: 18000,
},
user: {
property: "data",
autoFetch: true,
},
endpoints: {
login: { url: "{your google auth API}", method: "post" }, // <-- should return response with token on it
logout: { url: "/api/profiles/logout", method: "get" },
user: { url: "/api/profile", method: "get" },
},
}

Unable to parse JSON

I am making a request to an external API from my node server:
request("https://api.data.gov/ed/collegescorecard/v1/schools/?id=168421&api_key=", function(error, response, body) {
console.log(JSON.parse(body));
console.log(body.metadata);
console.log(JSON.parse(body.metadata));
});
The first console gives the output:
{ metadata: { total: 1, page: 0, per_page: 20 },
results:
[ { '1996': [Object],
'1997': [Object],
'1998': [Object],
'1999': [Object],
'2000': [Object],
'2001': [Object],
'2002': [Object],
'2003': [Object],
'2004': [Object],
'2005': [Object],
'2006': [Object],
'2007': [Object],
'2008': [Object],
'2009': [Object],
'2010': [Object],
'2011': [Object],
'2012': [Object],
'2013': [Object],
'2014': [Object],
ope6_id: 2233,
location: [Object],
id: 168421,
school: [Object],
ope8_id: 223300 } ] }
The second log gives me an 'undefined'
The third log gives me SyntaxError: Unexpected token u
Why? How do I access only the metadata or results field?
you are trying to use body when this is not the json object. You have used JSON.parse only to console log, but haven't stored the value
var jsonBody = JSON.parse(body)
console.log(jsonBody);
console.log(jsonBody.metadata);
alternatively you could have done this console.log(JSON.parse(body).metadata);. You are parsing body as a json and then getting metadata from that parsed json

AngularJS http get data doesn't match with the data sent out by the server

$http.get( 'http://api.com/?id=' ).
success(function(data, status, headers, config) { console.log(data); }
The data logged from here onto the browser console shows one of the nested list as empty.
Structure of data being sent out from server:
`Server data =
{
status_message : '',
ourVar: {
time: '',
date: '',
name: '',
list1: [],
list2: [],
group: [
aList:[
{
name: '',
id: '',
ourList: []
}
]
]
}
var2: [
{},
{},
{}
]
var3: [ a:{
a1:[
{},
{},
{}
]
},
b:{
b1:[
{},
{},
{}
]
},
]
}
}`
ourList is being shown up as empty while there is data coming from the server. This sounds weird but, it's happening. What's going wrong here ?
Does your console display anything else?
The problem might have occured due to CORS policy. Try this approach:
Angularjs issue $http.get not working
Or maybe you have not specified any GET parameters (in URL) for your request.
Once you provide more information I will update my answer.
Cheers

Sencha Touch JsonP Request TypeError Ext.data is undefined

at the moment I'm working on my first Sencha Touch Application and I run into a problem I spent lots of hours until now.
I tried to get the value from a cross domain Json to fill a nested list in my application.
When I run my code in browser everything works fine. The List is filled and I can call a detail view by tap on a leafitem.
But after building the sencha touch app with "sencha app build", I only get the following error in the browser console when starting the app.
TypeError: Ext.data is undefined
Ext.data.JsonP.callback1({ Here is the long valid JSON content });
I don't unterstand, why Ext.data is undefined. I would appreciate if someone could help me. I tried several solutions but I couldn't get this running.
These are the contents of my files:
Store:
Ext.define("Test.store.ExpStore", {
extend: "Ext.data.TreeStore",
requires: [
'Ext.data.JsonP'
],
config: {
model: "Test.model.ExpModel",
proxy: {
type: 'jsonp',
url: 'http://myurl/project/mylist.php',
callbackKey: 'callback',
reader: {
type: 'json',
rootProperty: 'experts'
}
}
}});
Model:
Ext.define('Test.model.ExpModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'name', type: 'string'},
{name: 'number', type: 'string'},
{name: 'active', type: 'boolean'}
]
}});
ListView:
Ext.define('Test.view.ExpListView', {
extend: 'Ext.NestedList',
alias: 'widget.expListView',
config: {
fullscreen: true,
title: "Experts",
displayField: 'name',
store: 'ExpStore',
}});
app.json
"js": [
{
"path": "touch/sencha-touch.js",
"x-bootstrap": true
},
{
"path": "bootstrap.js",
"x-bootstrap": true
},
{
"path": "app.js",
"bundle": true, /* Indicates that all class dependencies are concatenated into this file when build */
"update": "delta"
}],
app.js
Ext.application({
name: 'Test',
requires: [
'Ext.MessageBox',
//'Ext.data.JsonP',
'Ext.data.*'
],
models: [
'ExpModel'
],
views: [
//'Main'
'ExpDetailsView',
'ExpListView'
],
controllers: [
'ExpController'
],
stores: [
'ExpStore'
],
icon: {
'57': 'resources/icons/Icon.png',
'72': 'resources/icons/Icon~ipad.png',
'114': 'resources/icons/Icon#2x.png',
'144': 'resources/icons/Icon~ipad#2x.png'
},
isIconPrecomposed: true,
startupImage: {
'320x460': 'resources/startup/320x460.jpg',
'640x920': 'resources/startup/640x920.png',
'768x1004': 'resources/startup/768x1004.png',
'748x1024': 'resources/startup/748x1024.png',
'1536x2008': 'resources/startup/1536x2008.png',
'1496x2048': 'resources/startup/1496x2048.png'
},
launch: function() {
// Destroy the #appLoadingIndicator element
Ext.fly('appLoadingIndicator').destroy();
var expListView = {
xtype: 'expListView'
};
var expDetailsView = {
xtype: 'expDetailsView'
};
// Initialize the main view
Ext.Viewport.add(expListView, expDetailsView);
},
onUpdated: function() {
Ext.Msg.confirm(
"Application Update",
"This application has just successfully been updated to the latest version. Reload now?",
function(buttonId) {
if (buttonId === 'yes') {
window.location.reload();
}
}
);
}});