Reading url passed data in node.js routes - node.js

I'm passing a data of a variable in URl from an python as
response = urlopen("localhost:5000/warehouse?fruitid=103456",timeout=10);
data = json.loads(response.read().decode('utf8'));
And it reading the response in json format for further processing.
How can I write the node.js routing for posting the data which reads the passed variable value of fruitid=103456 and insert the timestamp into the database when this request occurs.
Please help me out__...

try this - i use this to parse out json responses from other sources...
import pandas as pd
data1=dict(field1=data['field1_in_response'], field2=data['field2_in_response'],...);
data1=pd.DataFrame(data1)
print(data1)

const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql')
var squel = require("squel");
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'toor',
database: 'invoice'
});
app.get('/warehouse', (req, res) => {
let fruitid = req.query.fruitid;
let queryDashboard = "select * from fruit where fruitid ='"+fruitid +"'";
connection.query(queryDashboard, function (err, rows, fields) {
if (err) throw err
console.log('query get successful');
var result = rows.map(data => data.name);
res.send(result);
// connection.end()
})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));`enter code here`

Here's how you could handle this kind of request in an Express/MongoDB app:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const port = 5000;
app.get('/warehouse', (req, res) => {
console.log('fruitid:', req.query.fruitid);
MongoClient.connect('mongodb://localhost:27017', function (err, client) {
if (err) throw err;
const db = client.db('mydatabase');
db.collection('fruits').find({ id: req.query.fruitid }).toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Related

Node JS to SQL SERVER get null empty when i trying conect

var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database

Express can't start the server or connect to MongoDB

I'm a beginner and try to create a rest API following this tutorial. I expected to see Server is running on port: ${PORT}, but it seems like my code can't reach it. I got no error on my terminal and it looks like this
Here are my code:
server.js
require('dotenv').config({ path: './config.env' });
const express = require('express');
const cors = require('cors');
const dbo = require('./db/conn');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./api/api'));
// Global error handling
app.use(function (err, _req, res) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
});
conn.js
const MongoClient = require('mongodb').MongoClient
const dotenv = require("dotenv")
dotenv.config()
const connectionString = process.env.MONGOURI
let db;
module.exports = {
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
db = client.db('db-name');
console.log('Connected to Database');
return callback
});
},
getDb: function () {
return db;
}
}
api.js
const express = require("express");
const gameRoutes = express.Router();
const dbo = require('../db/conn');
gameRoutes.route("/game").get(async function (_req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("game")
.find({}).limit(50)
.toArray(function(err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
})
})
module.exports = gameRoutes;
Can you please tell me what's wrong with my code? I really can't find why the server is not running. Thanks in advance! I'll be very grateful for your help!
In your connectToServer method you just returning the callback. But you actually need to call it as well.
So change this
return callback
to this
return callback(null);
If you want to pass the possible error from MongoClient to the callback as well, then change your connectToServer method to this :
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) { return callback(err); }
db = client.db('db-name');
console.log('Connected to Database');
return callback(null) // no error, so pass "null"
});
}

How do I get data from a MongoDB collections using node.js and render it as a JSON in expess

I'm trying to get data from a collections database in my MongoDB using Node, which I've done successfully. My only problem is how to render the obtained data from the collections and posting it into the express app.
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close()
})
})
}
main().catch(console.error)
I solved my own problem by just performing an app.get() in the part were it says Mongoclient.connect() and the rest is done by logic, it displays now in the express and in postman as well.
const {MongoClient} = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {res.json(result)})
db.close()
})
})
app.listen(4000, function() {
console.log("listening to port 4000)
}
main().catch(console.error)
Here is another way:
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const port = 3000;
app.listen(port);
// Type this in your browser to see db data: http://localhost:3000/
app.get('/', function(req, res) {
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(function(err) {
console.log("Connected to server.");
const db = client.db(dbName);
db.collection("books")
.find({})
.toArray(function(err, result) {
if (err) throw err;
client.close();
console.log("Done reading db.");
res.send(JSON.stringify(result));
});
});
});

req.body undefined...how can i solve

[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
app.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
app.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));
Describe the bug
I am trying to send form data to my API but req.body is undefined for some reason.
To Reproduce
Steps to reproduce the behavior:
create a new request
enter your API endpoint URL
select the body tab and then select the form-data tab
enter the key name of the form data you are trying to send so your API can recognize it and then the value.
Click send and you should get a response with a status code of 200. If you get an error like me telling me that req.body is undefined then you have the same problem as me.
You are using bodyparser.json(). From the documentation, this will parse requests that are only in JSON. You are better off using bodyParser.urlencoded([options]).
I advise using express.urlencoded instead.
Read this for clarification
you are missing the router
[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
// u need a router
const router = express.Router();
router.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
router.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
router.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.use(router);
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));

NODE.js Insert into SQL Server

I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.

Resources