How can i list data from table in the database in a browser - javascript

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?

Related

Trouble opening localhost with Node and mssql

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

Bind problem in SQL query in Node, Express, Mysql2 app

I have been following a tutorial on setting up REST APIs in Node, using Express for an app that accesses an existing MariaDB database. My version only needs to read data and I have the DB co-located with the Node application (same host).
My goal for this entry-level example is to just access the data, using static SQL, so I can see it rendered in the web page by the JSON pritifier.
[Next, I want to present the data in a table (EJS?). Later, when I can get that to work, I'll add form controls (React?) to let a user specify start and end date bounds for the SQL query. Finally I'll aim to render the data as a line graph (D3js).]
The tutorial runs the web server successfully (it returns 'OK' on the base URL), but when I go to URL/solarData it tries an async function to getMultiple rows from the DB, it responds:
Bind parameters must not contain undefined. To pass SQL NULL specify JS null TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
at /SunnyData/solarViz/node_modules/mysql2/lib/connection.js:628:17
at Array.forEach (<anonymous>)
at Connection.execute (/SunnyData/solarViz/node_modules/mysql2/lib/connection.js:620:22)
at /SunnyData/solarViz/node_modules/mysql2/promise.js:120:11
at new Promise (<anonymous>)
at PromiseConnection.execute (/SunnyData/solarViz/node_modules/mysql2/promise.js:117:12)
at Object.query (/SunnyData/solarViz/services/db.js:6:40)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Object.getMultiple (/SunnyData/solarViz/services/solarData.js:7:16)
at async /SunnyData/solarViz/routes/solarData.js:8:14
app.js:61
./app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3800;
const solarDataRouter = require('./routes/solarData');
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.get('/', (req, res) => {
res.json({'message': 'ok'});
})
app.use('/solarData', solarDataRouter);
/* Error handler middleware */
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
console.error(err.message, err.stack);
res.status(statusCode).json({'message': err.message});
return;
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
./routes/solarData.js
const express = require('express');
const router = express.Router();
const solarData = require('../services/solarData');
/* GET solar data. */
router.get('/', async function(req, res, next) {
try {
res.json(await solarData.getMultiple(req.query.page));
} catch (err) {
console.error(`Error while getting solar data `, err.message);
next(err);
}
});
module.exports = router;
./config.js
const env = process.env;
const config = {
db: {
host: env.SUNNY_HOST,
user: env.SUNNY_USER,
password: env.SUNNY_PW,
database: env.SUNNY_DB,
},
listPerPage: env.LIST_PER_PAGE,
};
module.exports = config;
./services/solarData.js
const db = require('./db');
const helper = require('../helper');
const config = require('../config');
async function getMultiple(page = 1){
const offset = helper.getOffset(page, config.listPerPage);
const rows = await db.query(
`SELECT * FROM DTP LIMIT ?,?`, [offset, config.listPerPage]
);
const data = helper.emptyOrRows(rows);
const meta = {page};
return {
data,
meta
}
}
module.exports.getMultiple = getMultiple;
./services/db.js
const mysql = require('mysql2/promise');
const config = require('../config');
async function query(sql, params) {
const connection = await mysql.createConnection(config.db);
const [results, ] = await connection.execute(sql, params);
return results;
}
module.exports = {
query
}
I've left out the ./helper.js
Everything runs fine until I direct the webpage to /solarData. At that point I get the Debug Console (vscode) mentioned up-front
Searching seems to point at a mysql2 shortcoming/bug but not at a practical solution
If you respond, please describe the 'bind' mechanism, as I'm not sure what's going on.
Hope I've put enough info in. Please ask if I need to add anything else.
The error says
Bind parameters must not contain undefined.
It means that in the file ./services/solarData.js on the line
const rows = await db.query(
`SELECT * FROM DTP LIMIT ?,?`, [offset, config.listPerPage]
);
Some of the 2 variables is undefined, you need to check offset and config.listPerPage to be defined.
Just use
console.log('offset: ' + offset)
console.log('listPerPage: ' + config.listPerPage)
and you will find out what is undefined in your case

Apple-pay with Stripe not recognized in Dashboard

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')
})

Getting cannot POST / error in Express

I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});

Calling Express Route internally from inside NodeJS

I have an ExpressJS routing for my API and I want to call it from within NodeJS
var api = require('./routes/api')
app.use('/api', api);
and inside my ./routes/api.js file
var express = require('express');
var router = express.Router();
router.use('/update', require('./update'));
module.exports = router;
so if I want to call /api/update/something/:withParam from my front end its all find, but I need to call this from within another aspect of my NodeJS script without having to redefine the whole function again in 2nd location
I have tried using the HTTP module from inside but I just get a "ECONNREFUSED" error
http.get('/api/update/something/:withParam', function(res) {
console.log("Got response: " + res.statusCode);
res.resume();
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
I understand the idea behind Express is to create routes, but how do I internally call them
The 'usual' or 'correct' way to handle this would be to have the function you want to call broken out by itself, detached from any route definitions. Perhaps in its own module, but not necessarily. Then just call it wherever you need it. Like so:
function updateSomething(thing) {
return myDb.save(thing);
}
// elsewhere:
router.put('/api/update/something/:withParam', function(req, res) {
updateSomething(req.params.withParam)
.then(function() { res.send(200, 'ok'); });
});
// another place:
function someOtherFunction() {
// other code...
updateSomething(...);
// ..
}
This is an easy way to do an internal redirect in Express 4:
The function that magic can do is: app._router.handle()
Testing: We make a request to home "/" and redirect it to otherPath "/other/path"
var app = express()
function otherPath(req, res, next) {
return res.send('ok')
}
function home(req, res, next) {
req.url = '/other/path'
/* Uncomment the next line if you want to change the method */
// req.method = 'POST'
return app._router.handle(req, res, next)
}
app.get('/other/path', otherPath)
app.get('/', home)
I've made a dedicated middleware for this : uest.
Available within req it allows you to req.uest another route (from a given route).
It forwards original cookies to subsequent requests, and keeps req.session in sync across requests, for ex:
app.post('/login', async (req, res, next) => {
const {username, password} = req.body
const {body: session} = await req.uest({
method: 'POST',
url: '/api/sessions',
body: {username, password}
}).catch(next)
console.log(`Welcome back ${session.user.firstname}!`
res.redirect('/profile')
})
It supports Promise, await and error-first callback.
See the README for more details
Separate your app and server files with the app being imported into the server file.
In the place you want to call your app internally, you can import you app as well as 'request' from 'supertest'. Then you can write
request(app).post('/someroute').send({
id: 'ecf8d501-5abe-46a9-984e-e081ac925def',
etc....
});`
This is another way.
const app = require('express')()
const axios = require('axios')
const log = console.log
const PORT = 3000
const URL = 'http://localhost:' + PORT
const apiPath = (path) => URL + path
app.get('/a', (req, res) => {
res.json('yoy')
})
app.get('/b', async (req, res) => {
let a = await axios.get(apiPath('/a'))
res.json(a.data)
})
app.listen(PORT)

Categories