How do I get back data from a database using express.js without the result being undefined - sql

`I've been trying to display a database product with react but none of my approaches seem to work.
This is my node.js/express code :
const express = require('express');
const database = require('./config/database');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 3001;
const app = express();
app.use(express.json());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/products/:productId', (req, res) => {
console.log('request recieved');
const productId = req.params.productId;
const query = `SELECT * FROM products WHERE product_id = ${productId}`;
database.query(query, (err, result) => {
if (err) console.log(err);
console.log(result);
res.send(result);
});
});
app.listen(PORT, 'localhost');
I tried to fetch and log it with axios but the results are undefined :
const productId = params.productId;
const url = `/product/${productId}`;
const [{data, loading, error}] = useAxios(url);
console.log(data);
I also tried the regular approach :
const fetchProduct = async (url) => {
try {
const response = await fetch(url);
console.log(response);
const data = await response.json();
console.log(data);
} catch(err) {
console.log(err);
}
return data;
}
const product = fetchProduct(url);
console.log(product);`
Some help would be appreciated

What if you create an arrow-function that it returns a Promise
const getById = (productId) => {
const query = `SELECT * FROM products WHERE product_id = ${productId}`;
return new Promise((resolve, reject) => {
database.query(query, (err, result)=> {
err ? reject(err): resolve(result)
})
})
}
as our getById arrow-function returns a promise we need to async/await on it, so the app.get will be like this
app.get('/products/:productId', async(req, res) => {
console.log('request recieved');
const productId = req.params.productId;
const product = await getById(productId)
res.status(200).send(product)
});
One more thing, in your code you wrote
app.use(express.json());
and
app.use(bodyParser.json());
those two instruction do the SAME THING, so you need to delete one of them, and it better be the bodyParser one, because the body-parser is just deprecated and you don't need to install it, you just need to add
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

Related

Empty body using express post

I can't seem to get the data from this post call. The body shows as an empty object {}.
I've tried several versions including these posts with no luck: Express.js req.body undefined
I've also tried different content-types, but that also hasn't worked.
Thoughts? Thanks in advance.
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries.js')
const port = 7000
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', (req, res) => {
res.json({
info: 'Node.js, Express, and Postgres API'
})
})
app.post('/jothook/', jsonParser, db.jothook)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
queries.js:
const Pool = require('pg').Pool
const { req } = require('express');
const pool = new Pool({
user: 'testuser',
host: '167.XX.XX.XX',
database: 'testdb',
password: 'testpwd',
port: 5432,
})
const jothook = (req, res) => {
var qy = JSON.stringify(req.body);
var qy = 'INSERT INTO data_test VALUES ' + qy;
pool.query(qy, (error, results) => {
if (error) {
throw error
}
res.status(201).send(`Data Inserted`)
})
};
module.exports = {
jothook
};
post call:
{headers={Content-Type=application/json}, body="'test_data', 'joe', 'smith'", method=POST, mode=cors}

expressJS is preventing me to post a resource

I'm trying to build a mini app in express, the "database" I'm using is a local array object file, I can retrieve resources from this "database" but for some reason I'm not able to post (push) a new object to this object array. This is how the code looks like:
server.js:
const express = require('express');
const app = express();
const userRouter = require('./routes/user.js');
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.text());
app.use('/user', userRouter);
app.listen(3000, () => console.log(`listening at ${port}`));
user.js:
const express = require('express');
const BBDD = require('./BBDD.js');
const userRouter = express.Router();
userRouter.get('/:guid', (req, res, next) => {
const { guid } = req.params;
const user = BBDD.find(user => user.guid === guid);
if (!user) res.status(404).send()
res.send(user);
next();
});
userRouter.post('/', (req, res, next) => {
let user = {};
user.name = req.body.name;
user.id = req.body.id;
BBDD.push(user);
next();
});
module.exports = userRouter;
And this is my local "database" file I want to perform logical CRUD operations:
BBDD.js
const BBDD = [{
index: 0,
guid: "1",
name: "Goku"
},
{
index: 1,
guid: "2",
name: "Vegeta"
},
];
module.exports = BBDD;
this is how I try to post a new resource, and this is the error I get:
It seems to be in order, but it won't work and can't find the bug.
Remove the next and send a response .express is having trouble finding the next matching handler because there is none

Run socket.io from an express route

I have researched on this but nothing seems to satisfy my need. I have an express route connected to a mongodb. Below is part of the code.
const express = require('express');
const socketIo = require("socket.io");
const dbconnect = require("./models");
const handle = require("./handlers");
const routes = require("./routes");
const app = express();
app.use('/messages', routes.messages);
const PORT = 3000;
const server = app.listen(3000, function() {
console.log(`Listening on 3000`);
dbconnect().then(() => {
console.log("MongoDb connected");
});
});
const io = socketIo(server);
io.on('connection', function(client) {
console.log('Connected...');
});
My route looks like this:
const router = require('express').Router();
const handle = require('../handlers/messages');
router.post('/unread_messages', handle.unread_messages);
module.exports = router;
My handler looks like this:
const db = require("../models");
exports.unread_messages = async (req, res, next) => {
try {
const unreadmessages = await db.messages.countDocuments({ $and: [{receiver: req.body.receiver},
{ messageread: false }]});
return res.json({ unreadmessages });
} catch (err) {
return next({ status: 400, message: `Cannot get unread messages ${err}` });
}
};
I would like to add socket to the "/unread_messages" route so that I get an update of the count of unread messages in realtime. How do I do that?

Using Express Router with Next.js

I'm trying to use the Express Router with Next.js using their custom-express-server example as my boilerplate. The only difference is that I'm trying to define the routes externally on routes/router.js as follows:
Code in server.js:
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const routes = require('./routes/router')
app.prepare()
.then(() => {
const server = express()
server.use('/', routes)
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
module.exports = app;
Code in routes/router.js:
const express = require('express'),
app = require('../server.js'),
router = express.Router();
router.get('/a', (req, res) => {
return app.render(req, res, '/b', req.query)
})
router.get('/b', (req, res) => {
return app.render(req, res, '/a', req.query)
})
router.get('/posts/:id', (req, res) => {
return app.render(req, res, '/posts', { id: req.params.id })
})
module.exports = router;
At this point, even when I'm importing "app" from server.js, app is not available within router.js.
Is my logic incorrect?
If it's not, then why is app not available within router.js?
Just solved it. This issue is known as a circular dependency, and it should be avoided at all costs... unless the pattern you're using (like the boilerplate I used, I guess...) requires it.
To solve it, just export from file "A" the dependency that file "B" uses before you require file "B" on file "A".
...And that's it pretty much.
You might also try using next-routes, which I use on all of my Next project:
// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
createServer(handler).listen(port, err => {
if (err) {
throw err;
}
console.log(`> Ready on http://localhost:${port}`);
});
});
Then you can configure your routes in the routes.js file without accessing the app:
// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
routes
.add('landing', '/')
.add('blog', '/blog', 'blog')
.add('blog-post', '/blog/:postId', 'blog')

send serial port data to front-end with express & node

I want to send serial port data to a browser UI with express. So far my code looks like this:
var SerialPort = require("serialport");
var serialport = new SerialPort("/dev/cu.usbmodem1421");
var express = require('express');
var app = express();
var datenFromA;
serialport.on('open', function(){
console.log('Serial Port Opend');
serialport.on('data', function(data){
datenFromA = data[0];
console.log(datenFromA);
});
});
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000);
Instead of the 'Hello World' I want to send the value of variable datenFromA to the browser. Any ideas how to pass the value to the app.get function?
Thanks in advance.
Essentially you need to wait until you receive an event. Quick dirty example given below:
const SerialPort = require("serialport");
const serialport = new SerialPort("/dev/cu.usbmodem1421");
const express = require('express');
const app = express();
// Only need to do this once.
serialport.on('open', () => console.log('Serial Port Opend'));
app.get('/', async (req, res) => {
const promise = new Promise((resolve, reject) => {
serialport.on('data', (data, err) => {
if (err) {
reject(err);
return;
}
resolve(data[0]);
});
})
const data = await promise;
res.json(data);
})
app.listen(3000);