I am deploying a simple nodejs server to App-engine which works well except for the database connection using the X-devapi. I am getting this error:
All routers failed.
Here is the code I use:
'use strict';
const express = require('express');
const mysqlx = require('#mysql/xdevapi');
const app = express();
app.get('/', (req, res) => {
const options = { user: 'user_name', password: '#pass',host: 'XX.XXX.XX.XXX'
/*Here I used Public IP address on the of the SQL instance*/,port: XXXX
/*I assigned port 8080 here*/, schema: 'db_name' };
(async function () {
let session;
try {
session = await mysqlx.getSession(options);
const collection = await session.getSchema(options.schema).createCollection('collection');
await collection.add({ name: 'foo' }).execute();
await collection.find().fields('name').execute(console.log); // { name: 'foo' }
} catch (err) {
//console.error(err.message);
res.status(200).send(err.message).end();//used code 200 in order to receive the error too
} finally {
session && session.close();
}
})();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
How can I solve this?
It turns out that Google cloud SQL tools still do not have the X devAPI enabled if you check response to my concern here and the feature request here
Related
I was making one app with frontend react.js uses axios to api call and for backend i am using express and node with database mysql while making call to api url i am getting error for access denied error
Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''#'localhost' (using password: NO)
If this is not the case i will be getting axios network error
Axios Network error
i dont know which port to use if i use 3306 port it is already in use. Please take a look at code and suggest about optimization and a better way...
thank you....
config.js will be saving confiq for the connection db
config.js
const config = {
db: {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
},
};
module.exports = config;
db.js will create the connection
db.js
const mysql = require("mysql");
const config = require("./config");
var con = mysql.createPool(config);
module.exports = con;
this is where the express and app server is supposed to create
index.js
const express = require("express");
var mysql = require("mysql");
const cors = require("cors");
const app = express();
app.use(express());
app.use(cors());
const TablesRoutes = require("./routes/TablesRoutes");
//routes
app.use("/", TablesRoutes);
app.listen(8000, () => {
console.log("Running on port :8000");
});
api routes to call from frontend
routes
const express = require("express");
const {
postTableDes,
alterTable,
showTables,
} = require("../Controllers/Tables");
const tablerouter = express.Router();
tablerouter.get("/", showTables);
tablerouter.post("/", postTableDes);
module.exports= tablerouter;
where showing the table act
controller
const con = require("../Config/db");
//get tables
const showTables = async (req, res) => {
//try {
var sql = `show tables`;
const data = await con.query(sql, (err, res)=>{
if(err){
console.log(err);
res.status(404).json({ error: "No show table" });
return;
}
console.log(res);
res.status(202).json(data);
});
module.exports = showTables;
Try to change the config.js to (the createPool call does not expect an object with db property):
const config = {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
};
module.exports = config;
I have created my first app using expo and react native.
My backend is written in node.js (with express and axios) and connected to mysql database. I will be using get, post and put.
What I don't understand is how I move from a development environment to a production environment. In order to connect my API to an external server how do I go about setting up a baseURL which would replace my IP address and port in the below example?
Axios.post("http://53.183.245.150/:19056/location", body).then((response) => {
console.log(response);
}).catch(err => console.log(err))
I have searched online and all examples which they create an API only include running off the local server rather than creating a production app and setting up a remote server.
I would like to link the mobile app to my existing production DB (using mysql) and running off AWS. This DB is connected to my website which is up and running. My backend for my website is written in PHP.
Thank you for any guidance!
I have attached an example of my server as well.
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user:'root',
host:'my ip address here',
password:'',
database: 'myDB',
});
app.post('/login', (req, res) => {
const user = req.body.user;
const password = req.body.password;
db.query('SELECT * FROM users WHERE uidUsers = ? AND pwdUsers = ?', [user, password], (error, rows, fields) => {
if (error) console.log(error);
if (rows.length > 0) {
res.send(rows);
} else {
res.send(rows);
}
});
})
app.get('/trips', (req, res) => {
const driver = req.query.driver;
const companyId = req.query.companyId;
const status1 = req.query.status1;
db.query('SELECT * FROM trips WHERE driver = ? AND company_id = ? AND status_1 = ?', [driver, companyId, status1], (error, rows, fields) => {
if(error) console.log(error);
else{
console.log(driver)
res.send(rows);
}
})
});
const PORT = process.env.PORT || 19056;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
})
Why am I getting the following error? I have a small Nodejs app hosted on DigitalOcean. I am getting the following error "Cannot GET /isFavorite" when I run the following post command in Postman: "http://octopus-app-s7q5v.ondigitalocean.app:8080/isFavorite" with body JSON parameters of:
{
"userid": "101",
"petid": "1"
}
The route I have for the app is an app.post("/isFavorite") and not an app.get. It is connected to a MySQL database which is also hosted on DigitalOcean. I have included a small version of the code for the app below. Why would I be getting this error? When I add an app.get("/") and return a response of "Hello" that works. It runs locally. I have configured all the environment variables in DigitalOcean settings. I have the "ca-certificate.crt" in the root of my Nodejs app. DigitalOcean app platform says it builds and deploys fine on the server.
Also, regarding the console.logs I have added to the code, where are they stored? I can see the one which starts the webserver and listens but not any of the others. The app is listening on port 8080 and has an IP address of 0.0.0.0.
const bodyParser = require("body-parser");
const querystring = require('querystring');
const router = express.Router();
const app = express();
app.use("/", router);
const mysql = require('mysql');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.post("/isFavorite", (req, res) => {
try {
console.debug("isFavorite Start");
const conn = mysql.createConnection({
host: process.env.DBHOST,
port: process.env.DBPORT,
user: process.env.DBUSER,
database: process.env.DBNAME,
password: process.env.DBPASSWORD
});
console.log("isFavorite logged on to db");
let selectQuery = 'SELECT COUNT(*) c FROM Favorites WHERE userID = ? AND petID = ?';
let query = mysql.format(selectQuery,[req.body.userid, req.body.petid]);
conn.query(query,(err, response, fields) => {
if(err) {
console.log(err);
res.status(500).send("Error querying database.");
return;
}
// rows added
console.log("isFavorite");
console.log(response.length);
if (response.length > 0) {
console.log(JSON.stringify(response));
res.status(200).json({IsFavorite: response[0].c >= 1});
} else {
res.status(200).json({IsFavorite: false});
}
});
} catch (err) {
next(err);
}
});
let PORT = process.env.PORT || 3000;
let IP = process.env.IP || '127.0.0.1';
app.listen(PORT, IP, () => {
console.log('Server is running at port ' + PORT + ' and IP = ' + IP);
});
Hii I am connecting Mysql Workbench and Nodejs to which the connection is successful. After the connection I have made a single get request which to me seems correct but I am still getting an error in the Postman! Can anyone help me?Here is my code-
const express = require('express')
const app = express();
var mysql = require('mysql')
var bodyParser = require('body-parser')
// db connection ----
var con = mysql.createConnection({
host:'localhost',
user:'root',
database:'tutorial',
password:'root'
})
con.connect(function(err){
if(err){
console.log("Error connecting to db");
}
else{
console.log("Connection established ");
}
})
const port = 8080;
app.listen(()=>{
console.log("Server started at port",port)
})
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/customer/' , (req, res) => {
con.query('SELECT * FROM customer', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
} );
module.exports = { app }
And this is the error I am getting in postman-
This is the console for vs code-
This is the console of postman-
You did not set the port in listen
app.listen(port, ()=>{
console.log("Server started at port",port)
})
Have you explicitly set the port to 8080 somewhere else? Express generator creates a www file in the bin folder, where your can set the port.
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
You can also set the port in listen
app.listen(port, () => {
console.log("Server started at port", port);
});
I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!