I wonder if there is any way to access a Discord.Client instance from another file.
What I've tried:
posts.js
const express = require('express')
const router = express.Router()
router.post('/checkRole', function (req, res) {
const guild = client.guilds.find(guild => guild.id === '688678156374044803');
let member = guild.members.get(req.body.id); // member ID
// Here I get an error which says the 'guild' is undefined.
res.send(response);
});
module.exports = router
index.js
const Discord = require("discord.js");
global.client = new Discord.Client();
const express = require('express');
const postsRoute = require('./routes/posts')
app = express()
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/posts', postsRoute)
/* ... some other code ... */
client.login(config.token);
app.listen(8080);
module.exports = { client }
I've also tried a similar approach like this but it didn't work either. Lastly I tried to store the client instance as a global variable but still no luck. Is there any way to achieve this?
It seems like the problem is not the fact that you can't properly export the client, but that the code that you want to use it with runs when the client is not ready yet: in fact, you're getting an error that says that no guild was found with the .find method, but it means that the client has the .guilds property and a .find method.
The client exists, the problem is that your code run before the ready event is fired: to avoid that, you can require your module inside the ready event handler. Here's an example:
// index.js
client.on('ready', () => {
const postsRoute = require('./routes/posts')
let app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use('/posts', postsRoute)
app.listen(8080);
})
Related
I am having trouble being able to insert data into my collection, I'm not even sure I'm doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I'm trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.
file1.js file:
require('dotenv').config()
const User = require('./assets/js/data')
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect(process.env.url, { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB server');
})
// 1. Import the express module
const express = require('express');
// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
res.render('main')
});
app.get('/login', (req, res) => {
res.render('login')
});
app.post('/login', (req, res) => {
console.log(req.body.number);
})
app.listen(3000, (err) => {
console.log("running server on port")
if (err) {
return console.log(err);
}
})
data.js
const mongoose = require('mongoose');
const userData = new mongoose.Schema({
phoneNumber: String,
})
const User = mongoose.model('User', userData);
module.exports(
User,
)
This line has the error.
// error
module.exports(
User,
)
module.exports is not a function.
module.exports = User
// or
module.exports = { User }
if you do the first one, then required should be like this,
const User = require('./assets/js/data')
otherwise
const { User } = require('./assets/js/data')
More about module.exports
The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require('./assets/js/data')" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/
I have an index.js file where I:
initialize my Express app instance
include a router.js file that defines a POST endpoint
create a Socket.IO object
code as follows:
const http = require("http");
const express = require("express");
const router = require("./src/router");
// Create Express webapp
const app = express();
// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;
//Create Socket.IO instance
const io = require('socket.io')(server,{
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials:true
}
});
const cors = require('cors');
At the POST endpoint in router.js, I want to use the Socket.IO object like this:
const Router = require("express").Router;
const router = new Router();
router.post("/call",(req, res)=>{
let data = req.body;
let response = {
something:`${data.userID} requested a call length ${data.minutes}`
}
io.broadcast.emit(response);
res.send(JSON.stringify(response));
});
module.exports = router;
But this gives me the error:
ReferenceError: io is not defined
How do I make the io object available to this router.post() call? I tried making it a global in index.js via:
global.io = io;
but then the POST call gave me this error:
TypeError: Cannot read property 'emit' of undefined
also tried including io as a parameter in the module.exports function like:
const Router = require('express').Router;
const { tokenGenerator, voiceResponse } = require('./handler');
module.exports = function(io) {
const router = new Router();
router.post('/call', (req, res)=>{
const data = req.body;
const response = {
something: `${data.userID} requested a call length ${data.minutes}`,
}
io.broadcast.emit(response);
res.send(JSON.stringify(response));
});
return router;
}
and then requiring the router in index.js like:
const router = require('./src/router')(io);
but that gave the same Cannot read property 'emit' of undefined error.
Read the error message carefully.
but that gave the same Cannot read property 'emit' of undefined error.
You are successfully passing io.
The problem is that io.broadcast is undefined so it can't have an emit property.
You can find broadcast on a socket object, not on the server object itself.
First up, node is not my thing. Nevertheless I find myself trying to figure out how to combine pino/pino-http and express to deliver some formatted logs. This part I have achieved.
What I was attempting to figure out for a short while was how to pass express via app.use(logger) a logger object that has got some base properties injected into it.
I tried a bunch of stuff, including creating a child logger and passing that to pinoHTTP() but although that did not error, i'd end up getting very long log objects which seemed full of goop and undesirable content.
pseudo code
const express = require('express');
const pino = require('pino');
const log = pino({level: process.env.LOG_LEVEL || 'info'});
const childLogger = log.child({'exampleProp': 'example-value'});
const logger = require('pino-http')({
logger: childLogger
});
const app = express();
const port = 3000;
app.use(logger);
app.get('/', (req, res) => {
logger.info('Hello World');
res.send('Hello World!');
});
app.listen(port, () => {
console.log('Example app listening on port ${port}')
});
I have cloned a GitHub repo for reference. But i don't know what this .keys_dev refers to. Everything seems fine to me. But it is returning me error. Everything is in its place as expected. I hope anyone can help me. It requires stack that is unknown to me. It is requiring api that is already defined. I need to understand can anyone help?
const express = require("express");
const bodyPaser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
const users = require('./routes/api/users');
const level = require('./routes/api/levels');
const employee = require('./routes/api/employees');
const exception = require('./routes/api/exception');
const payslip = require('./routes/api/payslip');
const dashboard = require('./routes/api/dashboard');
const individualcost = require('./routes/api/individualcost');
const oneoffpayment = require('./routes/api/oneoffpayment');
const record = require('./routes/api/record');
const app = express();
//Body parser middleware
app.use(bodyPaser.urlencoded({ extended: false }));
app.use(bodyPaser.json());
app.use(cors())
//Db
const db = require("./config/keys").mongoURI;
//MongoDB connection
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport Middleware
app.use(passport.initialize());
//Passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/users', users);
app.use('/api/level', level);
app.use('/api/employee', employee);
app.use('/api/exception', exception);
app.use('/api/payslip', payslip);
app.use('/api/dashboard', dashboard);
app.use('/api/individualcost', individualcost);
app.use('/api/oneoffpayment', oneoffpayment);
app.use('/api/record', record);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App is running on port ${PORT}`));
const db = require("./config/keys").mongoURI;
This require is fetching application configurations from the local filesystem, in this case the db URI. Perhaps the author of the repo forgot to mention that detail? It's very likely that if you want to use a MongoDB you'll have to setup your own local or cloud database and create a file under config/keys that contains a mongoURI. This should look similar to this:
// this is the contents of ./config/keys
export default {
mongoURI: "mongodb+srv://project:your-mongo-uri-here",
};
If you're looking to start a mongo cluster on the cloud, I've been using cloud.mongodb for a small pet project, works like a charm and it has a free plan tier.
You can also run mongo locally and just point the mongoURI to your local mongo instance.
I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine