I'm using Node to connect to a Microsoft SQL Developer database. I've finally gotten my code to run without errors:
var sql = require('mssql/msnodesqlv8');
const express = require('express');
const app = express();
// Get request
app.get('/', function (req, res) {
// Config your database credential
const config = {
server: "xxxx",
driver:"xxxx",
database: "xxxx",
user: "xxxx",
password: "xxxx",
options:{
trustServerCertificate: true,
}
};
// Connect to your database
new sql.ConnectionError(config,function(err){
// Create Request object to perform
// query operation
var request = new sql.Request();
// Query to the database and get the records
request.query('select * from mydb',
function (err, records) {
if (err) console.log(err)
// Send records as a response
// to browser
res.send(records);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is listening at port 5000...');
});
But, when I go to :
http://localhost:5000/
It doesn't load, it says the page cannot be reached. What can I try to resolve this?
You're using the wrong thing to try and connect to SQL Server. You don't use new sql.ConnectionError(), you use sql.connect(). This error is causing your app to crash so nothing is listening on port 5000.
var sql = require('mssql/msnodesqlv8');
const express = require('express');
const app = express();
// Get request
app.get('/', function (req, res) {
// Config your database credential
const config = {
server: "xxxx",
driver:"xxxx",
database: "xxxx",
user: "xxxx",
password: "xxxx",
options:{
trustServerCertificate: true,
}
};
// Connect to your database
sql.connect(config,function(err){
// Create Request object to perform
// query operation
var request = new sql.Request();
// Query to the database and get the records
request.query('select * from mydb',
function (err, records) {
if (err) console.log(err)
// Send records as a response
// to browser
res.send(records);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is listening at port 5000...');
});
Run that (after having applied proper database connection configuration values) and then you should be able to open your browser and connect to http://localhost:5000
Related
I'm developing a web application using reactjs nodejs and mysql database.
I want to list the data created in a table i created in the database in the browser via a link(http://localhost:5000/api/v/companies) .What code should i write in a page created in reactsjs?
Here is the code in the file index.js the backend of the table i created :
const express = require("express");
const app = express();
const cors = require("cors");
const pe = require('parse-error');
const logger = require('morgan');
const database = require('./mysql');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false,
limit: '800mb'
}));
// CORS
app.options("*", cors());
app.use(cors());
database.connect(function(err) {
if (err) throw err;
console.log("==> MySQL Connected Successfully!");
// The main page
app.get('/', function (req, res) {
res.json({
version: 'v1',
status: true
});
});
const stations = require('./routes/stations');
const companies = require('./routes/companies');
app.use('/api/v1', [stations, companies]);
});
app.listen(5000, () => {
console.log("Server is running on port 5000");
});
process.on('unhandledRejection', error => {
console.error('Uncaught Error', pe(error));
});
as well as other files created in the backend
const database = require('./../mysql');
/**
* List all companies
*/
const getAllCompanies = async function(req, res, next) {
try {
database.query('SELECT * FROM infos_stations.Companies', function (err, result, fields) {
if (err) throw err;
return res.status(200).json(result);
});
} catch (err) {
return res.status(500).send({
code: 500,
status: false,
data: "Internal Server Error"
});
}
};
module.exports = {
getAllCompanies,
};
In the reactjs application, you have to install any library for HTTP
requests. Axios is a Javascript library used to make HTTP requests
from node.js or XMLHttpRequests from the browser that also supports
the ES6 Promise.
In the backend, You have to create a route that accepts the HTTP request from
Frontend.
app.post('/getdata', function (req, res) {
// database queries etc.
//sending response(database result)at frontend.
}
In reactjs you can create an HTTP request on a button click or can create a
request on component renders using the UseEffect hook.
axios({
method: 'POST',
url: 'htttp//localhost/getdata',
responseType: 'stream'
})
.then(function (response) {
// response.data have all data of database.
//store response data in any reactjs state.
});
Use Map Function of state array in which you store a response that contains all database records. How to map lists How to render an array of objects in React?
I've tried following the suggestion at this link: MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
and am aware that it is using cahcing_sha2_password instead of mysql_native. However, I've tried following the suggestions and am still receiving the same errors, trying to connect to the database with node.
Schema name: 'my_db'
//DATABASE CONNECTION SETTINGS
const APIServerPort = 3001;
const database = {
host: "localhost",
port: 3306,
user: "root",
password: "xxx",
database: "my_db"
};
module.exports = {
database,
APIServerPort
};
app.js file:
const express = require("express");
const app = express();
const router = express.Router();
const settings = require("./settings");
const routes = require("./routes");
const mysql = require("mysql");
const connection = mysql.createConnection(settings.database);
router.get("/employees", routes.employees.listAllEmployees);
app.use("/apis", router);
connection.connect(error => {
if (error) {
console.error("Error Connecting to the database: " + error);
return process.exit();
}
app.listen(settings.APIServerPort, () =>
console.info(`Server is running at port ${settings.APIServerPort}...`)
);
});
SQL Queries Ran:
CREATE USER 'root'#'localhost:3301/apis/employees' IDENTIFIED WITH mysql_native_password BY 'xxx';
FLUSH PRIVILEGES;
I'm still receiving the same error however.
mysql users are in the form 'root'#'localhost'. Urls are a node.js concept only.
As that user already exists create a new one:
CREATE USER myapplication#localhost
IDENTIFIED WITH mysql_native_password BY 'xxx';
GRANT ALL ON my_db.* TO myapplication#localhost`;
You don't need FLUSH PRIVILEGES.
I seem to have gotten backend index.js file working with an apple-pay payment request on the back-end. However the results do not show up in my Stripe dashboard. Spinning my wheels and cannot figure out why. Any help would be much appreciated.
Below is the code I am using on the back-end. When I press the pay button in Apple-Pay in the App, my terminal window shows "Payment requested" and "Success" messages.
I would then expect the USD amount to process in my stripe dashboard but I am gettin $0.00 and no activity. Any help would be wonderful!
// Add packages we need
const express = require('express')
const bodyParser = require('body-parser')
var stripe = require('stripe')('YOUR-SECRET-KEY')
// Create an express app
const app = express()
// Use body parser so we can parse the body of requests
app.use(bodyParser.json())
// Just a sanity check endpoint we can hit in the browser
app.get('/', function (req, res) {
res.send('This is the backend server for Metatoll Application!')
})
app.post('/pay', function (req, res) {
console.log('Payment requested')
var token = req.body.stripeToken
var amount = req.body.amount
var description = req.body.description
stripe.charges.create({
amount: amount,
currency: "usd",
description: description,
source: token,
}, function(err, charge) {
if (err !== null) {
console.log('error capturing')
console.log(err)
res.status(400).send('error')
} else {
console.log('success')
res.status(200).send('success')
}
});
})
app.listen(3000, () => {
console.log('Metatoll listening on port 3000')
})
Hiii,
Recently my elastic beanstalk server have started to become unresponsive and return's 504 gateway timeout. I suspect that my pool.connect is becoming unresponsive and there are no logs reporting error while connecting to pool but it stucks at connecting. My other controllers with no database query works fine.
This goes away when I restart the server but after some time same thing happens.
I making requests this way-
1) database.js
const pg = require("pg")
// setting timestamp for the postgres.
pg.types.setTypeParser(1184, function(stringValue)
{
console.log(stringValue)
return new Date(Date.parse(Date.parse(stringValue + "+0000")))
})
// configuration for postres for connecting.
const pgConfig = {
user: "USER",
database: "DATABASE",
password: "1234",
port: 5432
}
const pool = new pg.Pool(pgConfig)
module.exports = pool
2) somecontroller.js
const db = require("../database/database")
const constant = require("../utility/constant")
module.exports = function(req, res)
{
db.connect(function(err, client, done)
{
if(err)
{
done()
console.log(constant.error.db.CONNECT_CONSOLE, err)
return res.send({status: constant.status.ERROR, code: constant.error.db.CONNECT})
}
client.query("QUERY", [UID])
.then(result =>
{
// Processing this queries and Some other query.....
})
.catch(err =>
{
console.log(constant.error.db.QUERY_CONSOLE, err)
res.send({status: constant.status.ERROR, code: constant.error.db.QUERY})
})
done()
})
}
My every controller works in similar fashion.
Thanks,
First question here, so be kind ;)
I am configuring a Node.js server to connect to a MongoDB database in Modulus.io node.js hosting (really good stuff, worth checking it out), but I can't seem to properly stablish connection. Per the getting-started guide I get a connection uri in the format:
mongodb://user:pass#mongo.onmodulus.net:27017/3xam913
But that doesn't seem to work with the structure of the code I was trying to port to the server (had it running locally) because of the Server class argument structure with only host and port to define...
This is the code I am trying to adapt to the connection:
// server setup
var mongo = require('mongodb'),
mdbServer = mongo.Server,
mdbDb = mongo.Db,
mdbObjectID = mongo.ObjectID;
// open a connection to the mongoDB server
var mdbserver = new mdbServer('localhost', 27017, {auto_reconnect: true});
// request or create a database called "spots03"
var db = new mdbDb('spots03', mdbserver, {safe: true});
// global var that will hold the spots collection
var spotsCol = null;
// open the database
db.open(function(err, db) {
if(!err) {
// if all cool
console.log("Database connection successful");
// open (get/create) a collection named spotsCollection, and if 200,
// point it to the global spotsCol
db.createCollection(
'spotsCollection',
{safe: false}, // if col exists, get the existing one
function(err, collection) {spotsCol = collection;}
);
}
});
Any help would be much appreciated, thanks!
Looks like a couple of things:
The connection URL should be mongo.onmodulus.net
var mdbserver = new mdbServer('mongo.onmodulus.net', 27017, {auto_reconnect: true});
rounce is correct, the database name is auto-generated by Modulus.
var db = new mdbDb('3xam913', mdbserver, {safe: true});
Modulus databases will need authentication. Before you call createCollection, you'll have to call auth and pass it the user credentials that are setup on the project dashboard.
I'm a Modulus developer, and I know the DB name thing is not ideal.
Edit: here's full source for a working example. It records every HTTP request and then sends all requests back to the user.
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var app = express();
var server = new Server('mongo.onmodulus.net', 27017, { auto_reconnect: true });
var client = new Db('piri3niR', server, { w: 0 });
client.open(function(err, result) {
client.authenticate('MyUser', 'MyPass', function(err, result) {
if(!err) {
console.log('Mongo Authenticated. Starting Server on port ' + (process.env.PORT || 8080));
app.listen(process.env.PORT || 8080);
}
else {
console.log(err);
}
});
});
app.get('/*', function(req, res) {
client.collection('hits', function(err, collection) {
collection.save({ hit: req.url });
// Wait a second then print all hits.
setTimeout(function() {
collection.find(function(err, cursor) {
cursor.toArray(function(err, results) {
res.send(results);
});
});
}, 1000)
});
});
Wrong database name perhaps?
From the MongoDB docs on the subject '3xam913' is your database name, not 'spots03'.
var db = new mdbDb('3xam913', mdbserver, {safe: true});