express API extract data from URL - javascript

My api recives every 45 minutes a request:
GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}
I want my code to save {device}, {data}, {time} and {customData#trama} into different variables so I can parse it into readable values(all data it is send hexadecimal) and insert them into my database.
How do I take those values out of the URL?
Also, what is the purpose of req, res? I guess It stands for request, respond.Respond sends back to the client but, request? I dont really understand how it works. Im learning all this new, hope someone can help.
This is my API code, I tried it with postman and it works fine so far:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "mgr#stanpgtest",
host: "stanpgtest.postgres.database.azure.com",
database: "my db name",
password: "my pass",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"select now()",
(error, results) => {
if (error) {
throw error;
}
res.send(results);
}
);
});

You need to write the path in this format, then extract your params from req.params.
app.post("mediciones/sigfox_libelium/:device/:data/:time/:customData", (req, res) => {
const {device, data, time, customData} = req.params
}
I'm not sure what #trama is meant to be, but I guess you can't use # in the route pattern.

Related

What does 'dbo' stands for in MongoDB - Express app?

Here is the code example:
app.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
db/conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I've done some research and it stands for 'Database Owner' in SQL Server but it doesn't make sense here.
These code examples are from MongoDB official documentation and why do they assign connection instance as dbo if it really stands for Database Owner?
As the documentation provides no explanation for the choice of variable name, we can only guess. My best guess is that dbo stands for database object, considering the type of the export.
I think this is idiosyncratic usage mimicked from the SQL world where dbo is the default schema and abbreviates database owner.
Typically, and in the MongoClient documentation, I see just db = require("./db/conn"); But it appears here that the author's fingers are just used to automatically typing an o after typing db.
Humans are habitual imitators. I wouldn't think too much of it. It's just a variable name.
There is no restriction and built-in parameters name in nodejs.
You can use that according to your preference

Fetch Data from Snowflake to nodejs

I am trying to design an API using Snowflake and Nodejs. For that I am using the following things :
Express
ejs
snowflake-sdk (nodejs module)
I want to fetch data from snowflake and want to display it on my ejs webpage. Please help if anyone has fetched data and populated it on a webpage using nodejs and snowflake.
this is my server.js file
const express = require("express");
const app= express();
const sql = require("./snowflake");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true}));
app.set("view engine","ejs");
app.get("/", function(request,response){
response.render("index");
});
app.get("/request/:core", async function(request,response){
let core=await sql.getCore(request.params.core_name);
response.render("request",{request: core});
});
const http = require('http');
const port=3000;
const server=http.createServer(function(req,res){
})
const listener = app.listen(port,function(error){
if(error){
console.log("Something went wrong due :", error);
}
else{
console.log('Server is listening port '+port);
}
})
This is my database.js file. I am able to connect to snowflake and run queries but can't understand, how to fetch the query result on the ejs webpage.
const { initParams } = require('request');
const sql = require('snowflake-sdk');
const connection = sql.createConnection({
account: 'account_name',
authenticator: 'SNOWFLAKE',
username: 'username',
password: 'password',
database: 'database',
schema: 'schema'
});
module.exports.getCore = async() =>{
connection.execute({
sqlText: 'Select column from Table_name',
complete: async function(err,stmt,rows){
let pool= await sql.connect();
return rows;
}
})
}
There is a sample application that you can try to compare, is written on node.js. It is a Citi Bike dashboard that lets users view bike usage over time and in differing weather conditions. The source code is available on GitHub.
More details: https://quickstarts.snowflake.com/guide/data_app/#4

Connecting to MySQL Database from React?

I've been having problems with connecting to a database. It is a remote database and no matter what I do, it just doesn't work! I've searched all around to no avail. I'm using React for doing so. I just want to make a simple connection and be able to run some queries. Here's the code:
db.js component:
const mysql = require('mysql');
const db = mysql.createConnection({
/*THE VALUES BELOW ARE NOT THE ONES I HAVE TO USE*/
host: '11.111.11.11',
user: 'username',
password: 'password',
port: 'port',
database: 'database'
});
module.exports = db;
server.js in my backend folder:
const express = require('express');
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I'm not getting anything from it, not even the logged info I asked for in the console.log()
Thanks for the help, in advance.
You have just created the connection, however you need also use the connect function to connect to your database. So you need to add a line in your server.js, (I have put a comment near the line that you missed to write.
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
db.connect(); // you missed this line
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I think you can also do this in db.js before exporting db.

adding mongoDB to web app that is working with postgreSQL

I have a simple web applicatoin with nodeJS backend and postgreSQL database.
I need to add a mongoDB database that will also save the state off the application as backup.
Is it possible to add it without changing the app structure in a simple way?
my code:
postgres.js file:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'postgres',
host: 'localhost'
database: 'tasks',
password: 'password',
port: 5432,
});
const getTasks = (request, response) => {
// get tasks query
};
const getTaskById = (request, response) => {
// get task by id query
};
const createTask = (request, response) => {
// create task query
};
const updateTask = (request, response) => {
// update task query
};
const deleteTask = (request, response) => {
// delete task query
}
module.exports = {
getTasks,
getTaskById,
createTask,
updateTask,
deleteTask
};
index.js file:
const express = require('express')
const bodyParser = require('body-parser')
var cors = require('cors')
const app = express()
const port = 8080
const db = require('./db/postgres')
app.use(cors());
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
});
app.get('/tasks', db.getTasks);
app.get('/tasks/:id', db.getTaskById);
app.post('/tasks', db.createTask);
app.put('/tasks/:id', db.updateTask);
app.delete('/tasks/:id', db.deleteTask);
app.listen(port, () => {
console.log(`App running on port ${port}.`)
});
Thanks!
How complicated is the state of the application and how do you intend on keeping it updated? Perhaps using MongoDB as store for state snapshots is over-complicating things. Storing JSON in Redis is possibly a simpler route.
You should perhaps also ask yourself why you need to save the sate of the application if you already have the postgres database. What state does your backend produce that is auxiliary to the data in postgres?

My app post data into JSON however it also throws this error "http://localhost:5000/write net::ERR_CONNECTION_RESET"

Sorry if I don't post the correct details, this is my first hands-on project after going through online tutorials.
I'm using React, node with axios to build a web app that captures status(available, in a meeting, lunch etc) and the time spent on each status.
The app works fine, it captures and writes the data onto the backend(JSON) however, I keep getting this error on the console.
POST https://localhost:5000/write net::ERR_CONNECTION_RESET
Uncaught (in promise) ERROR: Network Error
I've tried to look for a solution but can't find one that is similar to the tech-stack I used. Also, my lack of sufficient knowledge don't help either.
Any lead or read or solution will help.
pasting my code below:
My frontend code to push data into JSON file
const saveJson = (posts) => {
//api URL //end point from node server / express server
const url = "http://localhost:5000/write";
axios.post(url, posts).then((response) => {
//console.log(response);
}); };
The server.js code
const express = require("express");
const bodyParser = require("body-parser");
//calling packages
const fs = require("fs");
const morgan = require("morgan");
const cors = require("cors");
//Declare app
const app = express();
const port = 5000;
//middlewares
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cors());
//default route for server
app.get("/", (req, res) =>
res.status(200).send({
message: "Server is running...",
})
);
const WriteTextToFileAsync = async (contentToWrite) => {
fs.writeFile("./src/data.json", contentToWrite, (err) => {
console.log(contenToWrite);
if (err) {
console.log(err);
} else {
console.log("Done writing to file...");
// res.json({ msg: "success" });
}
});
};
//Declare timerow/write route to accept incoming require with data
app.post("/write", async (req, res, next) => {
//take the body from incoming requestby using req.body and conver it into string
const requestContent = JSON.stringify(req.body);
await WriteTextToFileAsync(requestContent);
});
//404 route for server
app.use((req, res, next) =>
res.status(404).send({
message: "Could not find specified route requested...!",
})
);
//run server
app.listen(port, () => {
console.log(
`!!! server is running
!!! Listening for incoming requests on port ${port}
!!! http://localhost:5000
`
);
});

Categories

Resources