I'm using auth0 as my authentification services into my project. I really love it, but I have a problem when using custom database(MySql), I sure that I have configured the db.connection parameter to my remote shared hosting database in Plesk. It always show : "[Error] Script execution did not complete within 20 seconds. Are you calling the callback function?", When I trying to run "Create" script.
here the script :
function create (user, callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.23.16',
user : 'user',
password : 'pass',
port : '3306',
database : 'dbname' });
connection.connect();
var query = "INSERT INTO users SET ?";
var insert = {
password: bcrypt.hashSync(user.password, 10),
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
}
What should I'm doing right now to solve this problem? I'm new to this
Thanks..
Regards,
fxbayuanggara
You're trying to connect to a local IP address (192.168.23.16), which will always fail since database scripts and rules are executed from Auth0's servers. You'll need to make your MySQL server accessible from Auth0's IP addresses, which at the time of writing are the following:
US domains: 138.91.154.99, 54.221.228.15, 54.183.64.135, 54.67.77.38, 54.67.15.170, 54.183.204.205, 54.173.21.107, 54.85.173.28
EU domains: 52.28.56.226, 52.28.45.240, 52.16.224.164, 52.16.193.66
Related
I'm writing an app in React Native and I have created a MySQL database to store my information, but I was wondering if it was possible to use axios or fetch to interact with my database since it's local and doesn't have an HTTP address yet?
I feel like I used to be able to do it, but I forgot the syntax to use... If anyone knows anything, I would greatly appreciate it.
Thank you
There is no direct connection between React Native and Mysql. So you need to use Node js.
Step 1:
npm install express
npm install body-parser
npm install mysql
Step 2:
const connection = mysql.createPool({
host : 'localhost', // Your connection adress (localhost).
user : 'root', // Your database's username.
password : '', // Your database's password.
database : 'my_db' // Your database's name.
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM users', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
To get the data in your React Native App. You need to use your PC's IP Address. If you use localhost you access the smartphone/emulator localhost. Here is an example to follow:
getData(){
fetch('http://yourpcip:3000/users')
.then(response => response.json())
.then(users => console.log(users))
I've created a simple mySQL database that I'm trying to access data from via an AWS Lambda function.
This is a version of the code that runs fine locally:
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query("SELECT username FROM ClimbingDB.users WHERE email = 'testemail1'", function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) throw error;
console.log(results);
process.exit();
});
});
This is that code converted to work with AWS Lambda:
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname
});
exports.handler = (event, context, callback) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
if (err) return callback(err)
// Use the connection
connection.query("SELECT username FROM ClimbingDB.users WHERE email = 'testemail1'", function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) return callback(error);
else return callback(null,results);
});
});
};
Which times out with this error message:
{
"errorMessage": "2019-07-19T17:49:04.110Z 2f3e208c-62a6-4e90-b8ec-29398780a2a6 Task timed out after 3.00 seconds"
}
I'm not sure why it doesnt seem to be able to connect. I tried adding the function to a vpc and a security group that has access to RDB's, neither of which do anything. I'm not sure what I'm doing wrong here.
You will need:
The Amazon RDS instance in the same VPC as the AWS Lambda function
A security group on the Lambda function (Lambda-SG)
A security group on the RDS instance (DB-SG) that permits inbound connections on port 3306 from Lambda-SG
That is, DB-SG should specifically reference Lambda-SG (it will turn into a security group ID in the format sg-1234).
You might also want to increase the timeout of the Lambda function to give it a bit more time to run.
I am using mysql and request. I want to make a request in my localhost server. I just need to know how to make the get request into the localhost server because I don't understand how, I'm running into a continuous loop.
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'virtual_currency_price'
});
Request:
router.get('/getprice', function(req, res){
request(connection, function (error, response, body) {
if (!error && response.statusCode == 200){
}
});
});
I'm trying to figure out how to do this but I'm failing very miserably
The table I'm trying to GET from is called "price" and I will be using the datetime to fetch certain prices.
After you establish a connection with your server you can use it to fetch data from database. You don't need to make a request using the module, just use the connection directly to execute queries as below:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'virtual_currency_price'
});
connection.connect();
connection.query('SELECT * from price', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
});
connection.end();
It's recommended that you create a pool of connections instead and reuse them in your app instead of creating it every time you need to access the DB.
See the docs from github.
How to use mysql connection with serverless framework.connection should be available in my component functions without creating mysql connection each time in component function
Tried like this
var mysql = require('mysql');
module.exports.respond = function(event, cb) {
var pool = mysql.createPool({
connectionLimit : 100,
host : 'hostname',
user : 'username',
password : 'password',
database : 'databasename',
debug : false
});
var message='';
pool.getConnection(function(err,connection){
if(err) {
message='Could not connect to database';
} else {
message="Database is connected";
}
var response = {
message: message
};
return cb(null, response);
});
};
but above code will be only available for current function,want to make common thing for mysql connection in serverless framework,can not find proper document about how to use mysql in serverless framework
I am writing answer of my own question
make database.js file in component/lib folder
code of database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'hostname',
user : 'username',
password : 'password',
database : 'databasename'
});
connection.connect();
module.exports = connection;
created object like this in component/lib/index.js file
var connection = require("../lib/database.js");
Can use connection variable to write mysql query like this in component/lib/index.js
module.exports.respond = function(event, cb) {
var query="SELECT * from table_name";
connection.query(query,function(err,rows) {
})
};
I believe you have a Component created in your Serverless Framework based project that contains multiple lambda functions. And now you want to write the MySQL connection code such that this code block is available for re-use in all your lambda functions of that component.
If this is the ask, then Serverless does provide a "lib" folder inside your Component directory, which you can utilize to write common code logic to be re-used. Since you have a NodeJS-based runtime for your component, there should be an "index.js" file inside your Component folder -
your_serverless_project_directory/component_name/lib/index.js
The first thing you want to do is to add the MySQL connection code logic to a function/method in index.js.
Serverless should have already included for you this entire lib/ folder in all your lambda function's handler.js code like this -
var lib = require('../../lib');
Therefore, the next/final thing you want to do is re-use your connection function/method (in all the lambda functions belonging inside your Component) like this -
module.exports.handler = function(event, context) {
lib.mySQLConnection();
};
Hope this helps, let me know how it goes.
To build off of Normal Goswami's answer:
You've specified the database here in the connection. My lambdas each need different databases, so in the connection code just leave off the database:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'hostname',
user : 'username',
password : 'password'
// no database here
});
connection.connect();
module.exports = connection;
And then use an oddly named function to change the database in each lambda function:
connection.changeUser({database: database}, function(err) {
if (err) { throw err; }
});
connection.query(sql, function(err, rows, fields) {
// etc
}
You could also look into using a database connection pool.
you have to make connection out of function, as we are doing it with mongodb
we are making mongodb connection out side of Lambda Function.
my code snippet from https://github.com/malikasinger1/serverles-practice/tree/master/mongodb-connection:
var mongoose = require("mongoose");
var dbURI = 'mongodb://localhost/mydatabase';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {//connected
console.log("Mongoose is connected");
// process.exit(1);
});
module.exports.signup = (event, context, cb) => {
//doing signup here
}
in your cace it will be something like this most probably:
var mysql = require('mysql');
//make connection here
var pool = mysql.createPool({
...
});
pool.getConnection(function(err,connection){
...
});
module.exports.respond = function(event, cb) {
//use connection here
};
I am assuming you are using serverless framework on AWS.
Although you can create a connection and assign it to a frozen variable, it's not guaranteed that your lambda won't create a new connection. Here is why:
The best way so far (in my personal opinion) is to create a separate lambda function for db related operations and invoke this function through other lambdas. Here is the flow:
client -> registerUserLambda -> dbLambda -> DATABASE
However, the thing about lambdas is that when there are too many requests, there will be new containers created to handle other requests. That is, new connections will be created. Therefore the concept of connection pools does not work well for now on serverless lambdas.
i have a question regarding about node.js for mysql.
I'm trying to check for changes in the database with node.js and every time it does a change it would do something.
I have the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialpodd',
});
connection.connect();
connection.query('SELECT * FROM personal', function(err, rows, fields) {
if (err) throw err;
console.log('Rows: ', rows[0].email);
});
connection.end();
But I want this code to be called once there is a change in the database. I know I could do a poll method, but it doesn't seem that effective and real-time. What would be a good real-time module that would allow me to do it, or is polling my only option?