I am making database connection with React-native. I want to capture the data I saved elsewhere in this class. But I'm having the problem I wrote below.
Error Code: const warnedKeys: {[string]: boolean} = {};
const AsyncStorage = require('react-native');
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
const db = mysql.createConnection({
});
db.connect();
AsyncStorage.getItem('155').then(value =>
console.log(value)
);
app.get('/', function(req,res){
var sql = 'SELECT ID FROM ...TBL_STT';
db.query(sql, (err, result)=>{
if(err) throw err;
console.log(result);
res.send(result);
});
});
app.listen(3210, ()=>{
console.log('Server aktif di port 3210')
});
There is no value assigned to your db variable. The const must be assigned an unconditional value, such as a letter in JavaScript.
You can change this value const db => let db
import {AsyncStorage} from 'react-native';
...
let db = mysql.createConnection({ });
Related
`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 }))
ive got a page which i call an api through getserversideprops to basically get all the data from a table. it used to work fine, but suddenly when i runned it today an error occured which i dont know the cause is. this is the response im getting when i console log the response
what i tried on my own and noticed to "help" was reducing the amount of columns that the API was selecting. For the api i used knex and express. this was the original code that used to work but now does not.
try{
let data = "";
await db.transaction(async (t)=>{
data = await db('sales').transacting(t)
.join('users','users.id','sales.cashier_id')
.join('customer','customer.customer_id','sales.customer_id')
.select('customer.name as customer_name','sales.sales_id','sales.date','sales.payment_type','sales.payment_status','sales.customer_id','sales.transaction_total','sales.total_paid','users.name','sales.shipment_fee','sales.days','sales.sale_type')
})
return data
}catch(e){
console.log(e);
throw e;
}
what i tried was reducing the amount of select columns to i think 5 or 6, but definitely if the amount of columsn i use is under a limit it works. like
try{
let data = "";
await db.transaction(async (t)=>{
data = await db('sales').transacting(t)
.join('users','users.id','sales.cashier_id')
.join('customer','customer.customer_id','sales.customer_id')
.select('customer.name as customer_name','sales.sales_id','sales.transaction_total','sales.date','sales.payment_type')
})
return data
}catch(e){
console.log(e);
throw e;
}
these are the attributes of my table
this is the server.js file of my expressjs
const compression = require('compression');
const express = require("express");
const app = express();
const fs = require('fs');
const http = require('http')
const https = require('https')
const PORT = process.env.PORT || 8000;
var cors = require('cors')
const mainRoutes = require('./api/v1/routes/index')
const cookieParser = require("cookie-parser");
app.use(compression());
app.use(cors( {origin: 'http://localhost:3000',credentials: true}))
// app.use(cors());
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// Main Routes
app.use("/api/v1", mainRoutes,(req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
this is how im calling the api from next
export async function getServerSideProps(context) {
try{
const res = await axios.get("/sales/get-all");
const data = await res.data
return { props: { data } }
}catch(err){
const data = "error"
return { props: { data} }
}
}
where i declared default url of the axios at the app.js file of next
import '../styles/globals.css'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8000/api/v1/"
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
im not quite sure what the problem is so pardon if the title of the question is not according to the problem i have.
EDIT:
i moved the api to a useeffect call, its now working. but why isnt it working in getserversideprops?
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?
Below you can see I have an Apollo server (using express). In lines 33-39 I use an express middleware to check an auth token and (if the token is valid) set the users _id onto the request object.
In my server constructor, I set the context to return the req, as well as the _id as the userId. I have also tried just doing ({req}) => {..req}.
No matter what I am trying, I am not getting acces to the userId in the apollo context. I've made a simple gql query resolver in Apollo to just log out the value, and it's always undefined.
Furthermore, I have a simple REST route (lines 43-49) that seem to attach the userId to every request just fine, so something isn't connecting, but I'm not sure where.
At the end of the day my goal is to receive a JWT token from a cookie sent client side, verify it, and add it the context so I can access the values in my graphQL resolvers. Any thoughts?
index.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const db = require('./db');
const User = require('./models/User');
const typeDefs = require('./gqlSchema');
const queries = require('./resolvers/queries');
const mutations = require('./resolvers/mutations');
const resolvers = {
Mutation: mutations,
Query: queries,
}
const app = express();
const corsOptions = {
origin: process.env.FRONTEND_URL,
credentials: true,
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
const { token } = req.cookies;
if (token) {
const tokenData = jwt.verify(token, process.env.SECRET);
req._id = tokenData._id;
}
next();
})
//// TEMP REST LOGIN ////
const login = require('./controllers/login');
app.post('/auth/google', login);
app.post('/token', (req, res) => {
console.log('/token middlware req: ', req._id);
res.send('test token route')
})
///////////////////
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
...req,
userId: req._id,
})
});
server.applyMiddleware({
app,
path: '/graphql',
cors: false,
});
app.listen({ port: 4000 }, () => {
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
})
I'm trying to create a really simple node API using express.js 4 but I need a few 'realtime' events for which I added socket.io. I'm fairly new to both so I'm likely missing something basic but I can't find good docs/tuts on this.
In the express app (created with the express generator) I have something like this based on simple examples and project docs that I read. This works OK and from client apps, I can send/receive the socket events:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var api = require('./routes/api');
var app = express();
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
// error handlers omitted
module.exports = app;
but I want to use the sockets from my API routes (in the ./routes/api.js file that I 'require' above). For example, someone might use the API to PUT/POST a resource and I want that broadcast to connected socket.io clients.
I cannot see how to use the 'io' variable or organise the code currently in the io.sockets.on('connection' ... function inside express routes. Here's the ./routes/api.js file:
var express = require('express');
var router = express.Router();
var io = ???;
router.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
io.sockets.emit('update', foo); // how?
});
module.exports = router;
One option is to pass it in to req object.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var api = require('./routes/api');
var app = express();
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
// Make io accessible to our router
app.use(function(req,res,next){
req.io = io;
next();
});
app.use('/api', api);
// error handlers omitted
module.exports = app;
./routes/api.js:
var express = require('express');
var router = express.Router();
router.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
req.io.sockets.emit('update', foo);
});
module.exports = router;
I've modified your files a little bit, may you check if it works?
You can pass the io you've defined to your routes like below;
require('./routes/api')(app,io);
I didn't test the Socket.IO parts but there is no syntax error and routes also working.
server.js file:
var express = require('express');
var app = express();
var path = require('path');
var logger = require('morgan');
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
require('./routes/api')(app,io);
console.log("Server listening at port 3000");
api.js:
module.exports = function(app,io) {
app.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
console.log("PUT OK!");
io.sockets.emit('update'); // how?
res.json({result: "update sent over IO"});
});
}
Supposing you want to access the SocketIO from anywhere in your application, not just in the router, you could create a singleton for it. This is what works for me:
//socket-singletion.js
var socket = require('socket.io');
var SocketSingleton = (function() {
this.io = null;
this.configure = function(server) {
this.io = socket(server);
}
return this;
})();
module.exports = SocketSingleton;
Then, you need to configure it using your server:
//server config file
var SocketSingleton = require('./socket-singleton');
var http = require('http');
var server = http.createServer(app);
SocketSingleton.configure(server); // <--here
server.listen('3000');
Finally, use it wherever you want:
//router/index.js
var express = require('express');
var router = express.Router();
var SocketSingleton = require('../socket-singleton');
/* GET home page. */
router.get('/', function(req, res, next) {
setTimeout(function(){
SocketSingleton.io.emit('news', {msg: 'success!'});
}, 3000);
res.render('index', { title: 'Express' });
});
module.exports = router;
One more option is to use req.app.
app.js
const express = require('express');
const path = require('path');
const logger = require('morgan');
const api = require('./routes/api');
const app = express();
const io = require('socket.io').listen(app.listen(3000));
// Keep the io instance
app.io = io;
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
// ...
app.use('/api', api);
module.exports = app;
routes/api.js
const express = require('express');
const router = express.Router();
router.put('/foo', function(req, res) {
/*
* API
*/
// Broadcast the updated foo..
req.app.io.sockets.emit('update', foo);
});
module.exports = router;
Refactored Edudjr's answer.
Change the singleton to create a new instance of socket.io server
const { Server } = require('socket.io');
const singleton = (() => {
this.configure = (server) => this.io = new Server(server)
return this
})();
module.exports = singleton
Initialise your express app, the server and the singleton.
// initialise app
const app = express();
const server = require('http').createServer(app);
// configure socket.io
socket.configure(server)
Then in your router
const socket = require('/utils/socket-singleton');
socket.io.emit('event', {message: 'your message here'})
I think best way is to set io as a property of req, like below:
app.use(function(req,res,next){
req.io = io;
next();
});
app.use('/your-sub-link', your-router);