AWS IOT createKeysAndCertificate gives network Failure ERROR - javascript

In the below code iot.listCertificates executes perfectly and i am able to see all certificates in AWS IOT console but when I try to execute command iot.createKeysAndCertificate it gives me NETWORK FAILURE ERROR.
Please help me with this,
Thank You!!
var params = {};
iot.listCertificates(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
alert("Attempting to create new thing!!");
params = {
setAsActive:false
};
iot.createKeysAndCertificate(params, function(err, data) {
if (err)
alert(err);
else
alert("New thing added to AWS IOT");
});

I just tried your code above from within a browser (Chrome 61) and it successfully listed the certificates and create new ones. So don't think the issue is with your code.
Maybe try ensuring the clock is correct on the machine your making the request from. I've see some AWS request fail due to the clock being off by a few minutes. They might also use the time in the request to generate the expiration date on the certificate.

Related

Javascript - How to insert a variable value into a database from MQTT

I've written a program that listens to a public MQTT channel and prints any incoming messages ---> this works well
I have a bit of code in the same program that can read and write from a local database I have ---> this works well
I want to insert the message that is printed from the MQTT channel INTO a table in my database.
I've looked around for solutions and tried all sorts, but I can't seem to get anywhere with the solutions and help in the other topics.
Edit: My table is called 'sensors' and it has 1 column called 'value'
EDIT2:
My function:
if (data) {
//do database update or print
console.log("----");
console.log("temp: %s", data);
connection.query('INSERT INTO sensors VALUES ??', [data], function (error, results, fields) {
// When done with the connection, release it.
//connection.release();
console.log(results);
// Handle error after the release.
if (error) throw error;
});
//reset to undefined for next time
data = undefined;
}
Currently fails to write to my table. but it can listen and read fine
Any suggestions?
I fixed my issue. It turned out to be a syntax error
here's the solution
if (data) {
//do database update or print
console.log("----");
console.log("temp: %s", data);
connection.query('INSERT INTO sensors VALUE (?)', data, function (error, results, fields) {
// When done with the connection, release it.
//connection.release();
console.log(results);
// Handle error after the release.
if (error) throw error;
});
//reset to undefined for next time
data = undefined;
}
});

when using fetch, axios, etc.`catch` doesn't handle the error, instead your app crashes

To make sure that our request will be successful, first, we check the internet connection then send our request.
like this:
NetInfo.isConnected.fetch().then(async isConnected=> {
if(isConnected){
try {
let result = await fetch(MY_REMOTE_SERVER);
console.log("result: ", result)
} catch (error) {
console.error("error: ", error);
}
}
else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});
Everything was fine, until I faced this issue: consider a situation in which access to a server for some countries is blocked.
So, although the internet connection is ok, each time I was getting network request failed error.
I couldn't find the problem because expected the catch to print the error, but my app was just crashing.
Now that I know the reason, I don't know how to solve it.
For example, when the connection can't be made I want to alert the user to use a VPN or leave the app because they are in an embargoed country!
On the other hand, what is the point of catch!? if it doesn't catch the error!
thanks.
Actually this is a mistake on our side, react-native will crash as it encounters console.error.
so by changing the above code to this version you will get rid of the red screen:
NetInfo.isConnected.fetch().then(async isConnected=> {
if(isConnected){
try {
let result = await fetch(MY_REMOTE_SERVER);
console.log("result: ", result)
} catch (error) {
// use "log" instead of "error"
console.log("error: ", error);
// or you may want to show a toast on error like
oastAndroid.show('No internet', ToastAndroid.SHORT)
}
}else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});

Error from nodejs server thrown not being passed back to AJAX

I have the following AJAX that will send the entered data to the node server and the controller will check whether such data exist in the database or not.
If I do enter the data correctly, then everything is working fine.
However, I tried enter anything that the database does not have and it immediately throw an error, causing the server to stop. The error said that I did not handle the event, so I tried with res.json(err) in the controller instead of throw new Error, hoping that the error will be passed back to AJAX under the error key, but it is still not working. The error still gets thrown and the node server terminate itself.
I would like the server to continue and alert to the user that the data that was entered is not in the database but I have no idea why my approach is not correct.
I was thinking of using this SO thread if I'm able to get the error message back first from server side.
jQuery Ajax error handling, show custom exception messages
To solve the server from stopping, I used the code in app.js that was referred from this link
How do I prevent node.js from crashing? try-catch doesn't work
I'm not sure whether should I use the accepted answer for my case.
function createProduct(inputval){
let inputAction = window.location.pathname;
$.ajax({
type: "POST",
url: inputAction,
data: {order: inputval.split('-')[0].trim(), lot: inputval.split('-')[1].substring(0,5)},
success: function(data) {
$('#product').val('');
//Another function to add HTML
display(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("XHR" + jqXHR)
console.log("Status" + textStatus)
console.log(errorThrown)
}
});
}
Controller File
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (!product || err){
throw new Error("The product entered returns null");
}
res.json(product);
});
};
Main File: app.js
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
});
You should use correct status code for your response. I suggest change your controller like below snippet
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (err){
res.status(500).end();//means internal server error
} else if (!product) {
res.status(404).end();//means product not found
} else {
res.json(product);
}
});
};
I finally figure it out thanks to feedback from other community, so I thought I would just share it here. It's so simple and silly me for neglecting such statement.
First, the code in app.js can just be removed.
Second, based on the answer given by #Milad Aghamohammadi. Instead of just:
res.status(500).end();
Use:
return res.status(500).json({err: "Server error"});
This way, the error is able to be handled by the AJAX error function and the node server will not be terminated from the event loop.

How to create Microsoft Account Sign-in to my website, similar to Google?

I'm working on a web project (HTML, CSS, JavaScript, with back-end in PHP). I've successfully got a Google Sign-in working, using their simple API, but can't get the Microsoft equivalent to function. The official online solutions to this seem to rely on .NET or PHP Composer. I'll try composer if that's the only way but a pure JS/PHP method would be easiest.
I've tried to use the following:
https://github.com/microsoftgraph/msgraph-sdk-javascript
https://github.com/AzureAD/microsoft-authentication-library-for-js
The code below is the closest I've come to a working solution. I can get some kind of user ID (which appears to be unique and constant for each user). This might be enough to set up the login system I want, but it would be ideal if I could also fetch their name and profile picture.
<script class="pre">
var userAgentApplication = new Msal.UserAgentApplication("MY CLIENT ID", null, function (errorDes, token, error, tokenType) {
// this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
})
userAgentApplication.loginPopup(["user.read"]).then(function (token) {
var user = userAgentApplication.getUser(); //this is good
//user.userIdentifier seems to be a unique ID
//I will store this and use it for future verification
console.log(user);
//START
// get an access token
userAgentApplication.acquireTokenSilent(["user.read"]).then(function (token) {
console.log("ATS promise resolved");
}, function (error) {
console.log(error);
// interaction required
if (error.indexOf("interaction_required") != -1) {
userAgentApplication.acquireTokenPopup(["user.read"]).then(function (token) {
// success
console.log("s2");
}, function (error) {
console.log("e2");
// error
});
}
});
//END
// signin successful
}, function (error) {
console.log(error);
// handle error
});
</script>
(this code won't run as I've pasted it because it relies on the MSAL script from the second github link, and needs an application client ID)
After getting the access token with scope user.read , you could call microsoft graph api to get sign-in user's profile information such as displayName , businessPhones :
https://graph.microsoft.com/v1.0/me
Content-Type:application/json
Authorization:Bearer {token}
To get user's profile photo :
GET https://graph.microsoft.com/v1.0/me/photo/$value
In addition , if you are using Microsoft Graph JavaScript Client Library in first link , you could get user's displayName and profile photo by :
client
.api('/me')
.select("displayName")
.get((err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res);
});
// Example of downloading the user's profile photo and displaying it in an img tag
client
.api('/me/photo/$value')
.responseType('blob')
.get((err, res, rawResponse) => {
if (err) throw err;
const url = window.URL;
const blobUrl = url.createObjectURL(rawResponse.xhr.response);
document.getElementById("profileImg").setAttribute("src", blobUrl);
});
Please refer to code sample here .

Clean up AWS err response

I will preface this post with I am very new to JavaScript and even newer to AWS and their services.
I am currently working through this AWS tutorial and I am adapting it to fit my needs. I am not asking to make this work, as I already have it working for my needs.
In this bit of code
userPool.signUp('username', 'password', attributeList, null, function(err, result){
if (err) {
alert(err);
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
});
I am having trouble reformatting the err received by the function call when something goes wrong.
For example, I am using AWS Lambda to check the input validation for server side (using python), and I have it raise Exception("First Name is not long enough") which is what i get in return. However, when the alert(err) is called, correctly, I receive this:
UserLambdaValidationException: PreSignUp failed with error First Name is not long enough..
I have tried split on the err but the console says split is not a function of err.
So my question is, how can I strip this err and only get the message instead of the whole exception?
I have already tried err.split("error"); err.value; err.errorMessage; err["value"]; err["errorMessage"]; err.Error; and it doesn't work.
Also, when I console.log(err) I am presented with:
Error: First Name is not long enough..(...) //the (...) is the stacktrace

Categories