I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them. i have looked at a number of similar questions on stackoverflow and have not been able to find an answer. Would appreciate if someone could please point out where i have gone wrong.
getListings.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config);
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
connection.query('SELECT listing_coords FROM listings', (err, rows) => {
if (err) throw err;
console.log('Data received from Db:\n');
var results = JSON.parse(JSON.stringify(rows));
module.exports = { results };
console.log(results);
});
});
Then in my script.js file i have
var { results } = require('./getListings');
console.log(results);
I am getting an error in the browser console saying "require is not defined"
I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way? Do i have to build an api and use ajax? Thanks in advance for any help.
have updated my getListings.js file - it now displays in the string of data i need in the browser as a raw data packet
var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
app.listen(5000, () => console.log('express server is running at 5000'));
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
I have been unsuccessful to get the output to run in script.js. I will post the working code when its working.
I am getting an error in the browser console saying "require is not defined"
It is because require is not an API for frontend. It should be the syntax of backend(eg. nodeJS).
Do i have to build an api and use ajax?
If you wanna to send data from frontend to backend. Using ajax is possible but the main point is you need to have a backend server(eg. using Express module for nodeJS) to connect with the database(eg. mysql, postgresSQL).
Update on 14 Feb, 2021
My practise for doing this is to use ajax to send a request to the backend server from frontend.
//frontend
$.ajax
({
url: "yourBackendServerUrl", //eg. localhost:8001/listing. Need modification based on your backend setting.
})
.done(function(data) {
console.log(data) //data should be the result from backend, then you can retrieve the data for frontend usage
});
For the CORS problem, you can install cors package. If you have a middleware in the global scope(a.k.a. app.use(cors()) ). Every time there are request, this middleware will run.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) // pay attention to this line of code.
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
The solution that I got to work is as follows:
getListings.js (this was nodeJS)
var mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
**app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});**// I believe this is a middleware function
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
app.listen(5000, () => console.log('express server is running at 5000'));// this can be any port that isnt currently in use
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
in my script.js file i was missing the following
$.get('http://localhost:5000/listings', function (data, status) {
console.log('Cords Data', data);
I believe that is the jQuery ajax
Then in the heading of my html I needed the following
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type = "module" defer src="script.js"></script>
thanks to everyone that helped me with this. especially #tsecheukfung01.
I dont fully understand all of the pieces so it will take me a while to fully understand this and be able to recreate this on my own. All part of the journey!
Related
So I have built my server like this:
var mysql = require('mysql2');
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
var PORT = 2096;
app.get('/getDataFromDatabase', function(req, res) {
console.log("Called")
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "casesdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM totalValues", function (err, result, fields) {
if (err) throw err;
res.status(200).send(result);
console.log("Test")
});
});
});
app.listen(PORT, () =>
console.log(`Example app listening on port ${PORT}!`),
);
and I'm calling it like this:
$( document ).ready(function() {
$.get('http://localhost:2096/getDataFromDatabase').done(function(data){
for (entry of data) {
dates.push(entry.date.split('T')[0]);
totalValues.push(entry.totalValue);
}
});
});
I have tested all of this on my local PC and it works just fine. I now uploaded it to my Ubuntu Server. Something I might want to add is that I'm using cloudflare and a domain to access the website of course. All request get refused like this (print in console):
GET http://localhost:2096/getDataFromDatabase net::ERR_CONNECTION_REFUSED
Any help is appreciated.
I believe it's because you are trying to access localhost but your express server isn't running on your local machine, it's on your domain.
Try:
http://<yourDomainHere>:3000/getDataFromDatabase
Also, your domain might be refusing any http requests by default.
Am new to Node.js and mysql. How can I get the results from GET request and use it in the POST in node.js
For example:
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'root',
host : 'localhost',
database : '',
password : ''
});
app.get('/get/pension/:empid', function (req, res) {
const empid = parseInt(req.params.empid);
connection.query("SELECT pensionid from pension where empid = ?",[empid], function(error,rows,fields){
if(!error){
console.log('connected inside');
res.send(rows);
}
else {
console.log('error 1' + JSON.stringify(error,undefined,2));
}
});
});
I want to use the pensionid from the GET request and insert into another table.
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
//should it be request.body? const {pension} = request.body
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)",[pension], function(error,rows,fields){
if(!error){
console.log('Added');
}
else {
console.log('error 1' + JSON.stringify(error,undefined,2));
}
});
});
Any help is much appreciated.
Thank you.
You could access the request body of a post request in the req object.
To parse the post body you have to add body-parser package to parse the request body.
First install the body-parser package.
>$ npm i --save body-parser
Then add the the package in your project file.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // To parse the Json data
And then access your body in req object.
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
const {pension} = req.body;
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Full working code:
var express = require('express');
var app = express();
var mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var connection = mysql.createConnection({
user: 'root',
host: 'localhost',
database: '',
password: ''
});
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
//should it be request.body? const {pension} = request.body
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
res.status(201).send("added");
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
res.status(500).send('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Please note that you have to send response in both error and success case.
I'm having issues setting up passport authentication with my server. I've used passportjs before but with mongodb. I'm currently trying to setup my local strategy with postgressql but have had no luck. When going to a login POST route with passport.authenticate(), I'm not getting a cookie sent back to me. I'm not sure if I setup my server correctly with passportJS and with my postgres database hosted via Heroku.
require('dotenv').config(); //In order to gain access to our .env file
//process.env.YELP_API_KEY
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json()); //This is going to allow us to access data stored in 'body' when making a post or put request
app.use(bodyParser.urlencoded({extended: true}));
const { Pool } = require('pg');
const fs = require("fs"); //This is needed to convert sql files into a string
let port = process.env.PORT || 5000;
//session-related libraries
const session = require("express-session");
const passport = require("passport"); //This is used for authentication
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
//Setting up our session
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
//Connection to database
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true
}); //This is used to connect to our remote postegres database hosted via Heroku
//initializing our session
app.use(passport.initialize());
app.use(passport.session()); //Telling our app to use passport for dealing with our sessions
//setting up our local strategy
passport.use('local', new LocalStrategy({passReqToCallBack: true},( username, password, cb )=> {
console.log("this is being executed");
pool.query("SELECT id, username, password from users where username=$1", [username], (err, result) => {
if(err){
return cb(err);
}
if(result.rows.length > 0){
const first = result.rows[0];
bcrypt.compare(password, first.password, (err, res) => {
if(res){
cb(null, {
id: first.id,
user: first.username
})
}
else {
cb(null, false);
}
})
}
else {
cb(null, false);
}
})
}));
passport.serializeUser(function(user, done){
console.log("serialize user is executing")
done(null, user.id);
})
passport.deserializeUser(function(id, done){
pool.query('SELECT id, username FROM users WHERE id = $1', [parseInt(id, 10)], (err, results) => {
if(err) {
return done(err)
}
done(null, results.rows[0])
});
});
app.post("/api/login", (req, res) => {
passport.authenticate('local', function(err, user, info){
console.log(user);
});
})
app.listen(port, function(){
console.log("Your app is running on port " + port);
});
Expected Results: user should be able to login with the post route "/api/login" but passport.authenticate is not working? Passport local strategy should also be correctly setup.
In your route app.post("/api/login", .... the passport.authenticate needs an access to the req and res.
There's more than one way to make it work.
app.post("/api/login", (req, res) => {
passport.authenticate('local', function(err, user, info){
console.log(user);
// make sure to respond to the request
res.send(user);
})(req, res); // <= pass req and res to the passport
})
// or
// use it as a middleware
app.post("/api/login", passport.authenticate('local'), (req, res) => {
console.log(req.user);
// make sure to respond to the request
res.send(req.user);
})
I am creating a simple web application using node.js, express and mysql.
When I connect to get /employees, I try to console.log the data of the linked DB. However, when connected to localhost, an infinite delay occurs.
What's wrong with me?
index.js
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json)
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'ps',
database: 'EmployeeDB'
});
mysqlConnection.connect((err) => {
if(!err)
console.log('DB connection succeded');
else
console.log('DB connection failed \n Error : '+ JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is running at port no:3000'));
app.get('/employees',(res, req)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
console.log(rows);
// console.log(rows[0].EmpID);
else
console.log(err);
})
});
You need to return something, like the data:
app.get('/employees',(req, res)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
res.json(rows);
else
res.status(500).send('Error found');
})
});
Also, parameters are reversed from normal – (res, req) vs. (req, res) as #JonathanLonowski catch it.
I'm trying to create a REST API using Node.js that would fetch the last N rows of a MongoDB collection. This is my current code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongodb = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
var db;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/sample", function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
}).limit(10,function(e,d){});
});
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");
This is successfully printing out all of the contents of the database on the server console (Whenever the client makes a get request). However, how do I give this JSON information to the client making the GET call instead in an efficient way (and one that supports the situation where the client can add a parameter N that would only fetch the last N rows of the database). I looked into Mongoose and that seemed pretty solid but in my case I already have a pre-existing database and collection so wasn't sure if that was the best route for this task.
If you need any more info or clarification, feel free to let me know! Thanks for reading!
Instead of res.end, you would use res.send and send the response back to the front end.
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
var response = {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.parse(doc)
}
res.send(response);
}
});
});
});
To get the last N records of a collection, you could use a combination of sort and limit. First, sort on a specific field such as date in ascending/descending order and then limit the results to whatever N is. Something like this:
db.collection.find({ query }).sort({ key: 1 }).limit(N)
UPDATE:
Based on our ongoing comment conversation, here is an example of how I have successfully sent data back to the client. This does not include the limit or anything fancy.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var db = require('./config/db');
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/', function(req, res) {
db.find({}, function(err, data) {
if (err) {
console.log(err);
return res.send(500, 'Something Went wrong with Retrieving data');
} else {
// console.log(data[0]);
res.json(data);
}
});
});
app.listen(port);
console.log('Server listening on port: ', port);
Ended up fixing my issue. Changed my get statement to this:
router.get("/", function(req, res, next) {
db.collection("samplecollection", function(err, collection){
collection.find({}).limit(10).toArray(function(err, data){
res.json(data);
})
});
});