createkeysand certificate aws javascript - javascript

I am implementing the following code using javascript in browser to create certificate and key pair:
var iot = new AWS.Iot();
function createCert(){
var params = {
setAsActive:false
};
iot.createKeysAndCertificate(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
};
and I am getting the ERROR as :
UnknownOperationException: null
at Object.s [as extractError] (https://sdk.amazonaws.com/js/aws-sdk-2.106.0.min.js:42:24512)
at constructor.o (https://sdk.amazonaws.com/js/aws-sdk-2.106.0.min.js:42:29401)
Please help me in resolving this error.
Thank You

Seems like I had configured AWS for dynamoDB and the endpoint of AWS.Iot was not updated.
Now, it works!!!

Related

TypeError: string.charCodeAt is not a function. How to encode object in node.js using express (restful api)

I use restful API with express & node.js and want to encode data to utf-8.
I install utf8 with npm install utf8
I set const utf8 = require('utf8');
I use utf8.encode(string) to object like that:
pool.query(`SELECT Station, Ime FROM auto_q_stations;`, function (error, result2, fields) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !" })
HQstationsAHS = result2;
res.json({ HQstationsAHS })
});
});
I receive error like that:
TypeError: string.charCodeAt is not a function
How to encode object in node.js using express (restful api) ?
My problem is the following, when I execute a query in a database, all data in Bulgarian are OK.
When I execute the query in node.is & express environment I receive the data like that:
"������-��������"
Please help, I really don't know how to fix this problem.
You should loop through your array and change every "Ime" field.
Something like
pool.query(`CALL Get_Discharge_Station('${dateNow}', ${daysBefore}, ${stNumber})`, function (error, result, fields) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !" })
HQstationsAHS = result2.map((item) => {
item.Ime = utf8.encode(item.Ime);
return item;
});
res.json({ HQstationsAHS })
});

Push Notification Using Amazon SNS (Node)

I am trying to implement push notification using Amazon SNS in Node. I have created a topic and published a message using below code
Create Topic
var createTopicPromise = new AWS.SNS({apiVersion: '2010-03-31'}).createTopic({Name: "TOPIC_NAME"}).promise();
// Handle promise's fulfilled/rejected states
createTopicPromise.then(
function(data) {
console.log("Topic ARN is " + data.TopicArn);
}).catch(
function(err) {
console.error(err, err.stack);
});
I got a TopicArn something like this arn:aws:sns:us-east-1:xxxxxxxxxx:TOPIC_NAME
Publish
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'REGION'});
// Create publish parameters
var params = {
Message: 'You Got Message!! Hello....', /* required */
TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxx:TOPIC_NAME'
};
// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();
// Handle promise's fulfilled/rejected states
publishTextPromise.then(
function(data) {
console.log("Message ${params.Message} send sent to the topic ${params.TopicArn}");
console.log("MessageID is " + data.MessageId);
}).catch(
function(err) {
console.error(err, err.stack);
});
Now the message have been published now I need to see this on my mobile. So I used subscribe code like this
var params = {
Protocol: 'application', /* required */
TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxx:TOPIC_NAME', /* required */
Endpoint: 'MOBILE_ENDPOINT_ARN'
};
// Create promise and SNS service object
var subscribePromise = new AWS.SNS({ apiVersion: '2010-03-31' }).subscribe(params).promise();
req;
res;
// Handle promise's fulfilled/rejected states
subscribePromise.then(
function (data) {
console.log("Subscription ARN is " + data.SubscriptionArn);
}).catch(
function (err) {
console.error(err, err.stack);
});
}
My question is what is Endpoint in Subscribe params. Where should I get this? and So far Am I right ? Please help me out.
Endpoint here is the ARN of your mobile application that you need to register with AWS. Here is the snippet from the official documentation
For Amazon SNS to send notification messages to mobile endpoints,
whether it is direct or with subscriptions to a topic, you first need
to register the app with AWS.
Source : https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html

ElasticSearch | The "data" argument must be one of type string, TypedArray, or DataView

I'm learning ElasticSearch (hosted on AWS).
I'm using the javascript sdk and this connectionClass.
My code:
let es = require('elasticsearch');
let client = new es.Client({
hosts: ['https://search-nboardelastic-xxyy.foo.es.amazonaws.com'],
connectionClass: require('http-aws-es')
});
function handler() {
let params = {
index: 'product',
q: 'bar'
};
client.search(params, (err, data) => {
if (err) {
console.log('Error ', err);
} else {
console.log('Data ', data);
}
})
}
handler();
Problem:
When I run the code I get the following error:
Error: Request error, retrying
POST https://https://search-nboardelasticxxyy.foo.es.amazonaws.com/product/_search => The "data" argument must be one of type string, TypedArray, or DataView
at checkRespForFailure (/Users/oscarandersen/WebstormProjects/peego/lambda/indexElasticSearch/node_modules/elasticsearch/src/lib/transport.js:266:18)
at done (/Users/oscarandersen/WebstormProjects/peego/lambda/indexElasticSearch/node_modules/http-aws-es/connector.js:48:7)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
at Function.Module.runMain (module.js:703:11)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
I cant figure out what the problem is, any help is appreciated.
I am not sure how useful this answer will be to you 4 months later but I ran into the same problem and the solution was to set the region for the AWS sdk. There are a number of approaches to this, the one I used was pulling in the aws-sdk to my server.js file and adding AWS.config.update({ region: "us-west-2" });

How can I fix set headers in node js?

I am trying to redirect from the condition of a mysql to a get method but it does not work. How could I solve it?
app.post('/responses/',(req,res)=>{
var {text, context ={} } = req.body;
var params = {
input: {text},
workspace_id: '07',
context
}`
`assistant.message(params,(err,response) => {
if(err){
res.status(500).json(err);
}
else {
res.json(response);
console.log(JSON.stringify(response, null, 2));
}
if(response.context.rfc){
var RFC = response.context.rfc;
connection.connect(function(err) {
if (err) throw err;
connection.query(`SELECT * FROM test where RFC = '${RFC}'`, function (err, result, fields) {
if(result.length){
console.log("login");
}
else {
console.log('no login');
res.redirect('/home'); //Her not redirect.
}
});
});
}
});
});
Because show this error: hrow err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
The error message indicates you are trying to set headers after the response is already sent. From your sample code, looks like your API call (whatever assistant.message is) is returning RFC. You then attempt to redirect to another page, but you've already called res.json, which begins sending a response to the browser.
You need to refactor your controller a bit so that you only call res.redirect or res.json, not both.

Meteor: Accounts._storedLoginToken is not a function

I am using CollectionFS with GridFS to upload images:
Pictures.insert(e.target.files[0], function(err, res) {
if (err) return console.log(err);
this.setState({editing: false});
});
However when uploading I get an error:
Exception in delivering result of invoking '/cfs.pictures.filerecord/insert':
TypeError: Accounts._storedLoginToken is not a function
I've tried calling Accounts._storedLoginToken() in the Meteor shell and it gives the same error.
The error occurs here in the Meteor code:
var authToken = '';
if (typeof Accounts !== "undefined") {
var authObject = {
authToken: Accounts._storedLoginToken() || '',
};
// Set the authToken
var authString = JSON.stringify(authObject);
authToken = FS.Utility.btoa(authString);
}
Any help would be much appreciated.
Did you add accounts-base to your project? Accounts object does not have the _storedLoginToken method until you add a certain pkg such as account-base.

Categories