Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 days ago.
Improve this question
I'm trying to confirm my app has successfully connect to my DB. I setup a test to use once I am connected, but am not seeing the results of it.
Right now I have a server.js file and a db.js file. When I connect I do see the Server is running on port 8080 message that comes from server.js However I am not seeing anything that is suppose be shown from db.js
I don't really know if this is working properly, or if I have done something that is canceling out the messages that db.js is suppose to show.
server.js
const express = require("express");
const app = express();
const port = process.env.PORT || 8080;
const db = require("./db");
db.startTest();
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
db.js
require("dotenv").config({ path: __dirname + "/.env" });
const MongoClient = require("mongodb").MongoClient;
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true });
function startTest() {
client.connect((err) => {
if (err) {
console.log("Unable to connect to MongoDB");
} else {
console.log("Connected to DB");
const db = client.db("test");
const sampleCollection = db.collection("sample");
sampleCollection.insertOne({ name: "Sample User" }, (error, result) => {
if (error) {
console.log("Unable to insert document into the collection");
} else {
console.log("Document inserted into the collection");
}
});
}
});
}
module.exports = {
startTest: startTest,
};
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have built an Express Server like this:
var mysql = require('mysql2');
var express = require('express');
var app = express();
var PORT = 3000;
app.get('/getDataFromDatabase', function(req, res) {
console.log("Called")
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "", // Password is filled ()
database: "casesdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM cases", function (err, result, fields) {
if (err) throw err;
res.status(200).send(result);
console.log("Test")
});
});
});
app.listen(PORT, () =>
console.log(`Example app listening on port ${PORT}!`),
);
My Goal is to call the /getDataFromDatabase in client javascript and then use that data. How would I go about that?
Try the following on client-side:
<script>
fetch('http://localhost:3000/getDataFromDatabase')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
</script>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So I use React to upload a file to my express server, doing this localy works however when I push the code to my nginx express server I keep on getting Cors errors. How would I be able to solve this problem, I currently user cors package ?
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
"preflightContinue": false,
"optionsSuccessStatus": 204
}))
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, databasepath + 'pdf-folder/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({ storage: storage })
router.post('/uploadfolder',[authJWT.authenticateJWT,authJWT.isAdmin,upload.single('file')], adminController.uploadfolder);
exports.uploadfolder = function (req,res,next){
let dates = JSON.parse(req.body.Dates)
const newFolder = new Folder_PDF(
{
name: req.file.originalname,
validFrom: dates.validFrom,
validTill: dates.validTill
}
);
newFolder.save((err,folder) => {
if(err){
return res.status(500).send({message: err});
}
return res.status(200)
})
}
And my front end is just a simple dataform, however since this is a cors error I bet it is a server error:
uploadFile = () =>{
let data = new FormData();
data.append( 'file', this.state.file, 'a file title' )
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
if( percent <= 100 ){
this.setState({ uploadPercentage: percent })
}
if(loaded === total){
// window.window.location.reload()
}
}
}
axios.post(apiLink+'admin/uploadfolder', data, options).then(res => {
}).catch(err => console.log(err))
}
The problem wasn't really cors, it was a 413 error. The file was to large, you have to set it in your nginx config file: client_max_body_size 2M;
const cors = require('cors');
const app = express();
const whitelist = ['yor-domain-name']
const corsOptionsDelegate = function (req, callback) {
let corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
I'm creating a real time chat app with socket.io, express and React.
My issue is that I get hundreds of polling requests until my browser basically crashes, I have no idea why.
I've tried to put a polling duration, a close timeout, a heartbeat interval, I've checked, both my socket.io and socket.io-client are on the same version.. I've tried everything could find on the web but nothing works.
I'm sure it's just a stupid little mistake that I just can't find, if you could help that would be great, thanks!
Here's my code :
import express from "express";
import socketio from 'socket.io';
import path from 'path';
import ioCookieParser from 'socket.io-cookie-parser'
import http from 'http';
const app = express()
const port = process.env.PORT || 8000
app.set("port", port)
const httpServer = new http.Server(app);
const io = socketio(httpServer);
io.use(ioCookieParser(secret));
io.on('connection', function (client) {
const userId = client.request.signedCookies._session;
const clients = new Map();
client.on('login', () => {
clients.set(userId, { client })
console.log("clients :", clients)
})
client.on('message', (message) => {
User.findById(userId, function(err, obj) {
if(err) {
console.log(err);
return null
}
let currentUser = obj["email"];
client.broadcast.emit("received", { message, currentUser });
Connect.then(db => {
console.log("connected correctly to the server");
let chatMessage = new Chat({ message: message, sender: currentUser});
chatMessage.save();
});
})
})
client.on('error', function (err) {
console.log('received error from client:', client.id)
console.log(err)
})
});
Here is an example of a request :
GET localhost:8000 /socket.io/?EIO=3&transport=polling&t=Mideit5&sid=OxvoE0uJbi9DZyk-AAt8 xhr
Thanks!
My issue was that, in the React component, I was declaring :
const socket = io.connect('http://localhost:8000')
inside the component.
I've moved this constant outside of the component and now the issue is solved!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm pretty new to Node so I apologize if this is a simple question. But I'm trying to read the contents of a directory, ./resources, then display links to them on the webpage. The catch is that the files in the directory are dynamic, so I'm using fs.readdir in Node.
But the <h1> is not showing on the index.html page; any ideas why?
const resDir = "resources/";
const resDirFiles = [];
const app = http.createServer((req, res) => {
...
fs.readFile(filePath, (err, content) => {
if (err) {
// To be implemented
} else {
res.writeHead(200, {
"Content-type": contentType
});
res.end(content, "utf8", callback(req, res));
}
});
});
function callback(req, res) {
if (req.url == "/" || req.url == "/index") {
fs.readdir(resDir, (err, files) => {
files.forEach(file => {
resDirFiles.push(file);
res.end("<h1>Ok</h1>"); // placeholder
});
});
}
}
This solution makes use of module http and it list all files in directory resDir. It also provides links to the files, but it doesn't work on all browsers/servers due to security concerns, to avoid giving a free gateway between the user and the server. For something more robust you should have a file server.
var path = require('path')
var http = require('http')
var find = require('find')
var resDir = __dirname
http.createServer(function (req, res) {
res.setHeader('content-type', 'text/html')
find.file(resDir, function (files) {
res.write('<ul>')
for (let i = 0; i < files.length; i++) {
let fileRelative = path.relative(resDir, files[i])
res.write('<li>' + fileRelative + '</li>')
}
res.write('</ul>')
res.end()
})
}).listen(3000, function () {
console.log('server start at port 3000')
})
Now you can access it on http://localhost:3000
You can straight away use lot of npm project for this, like http-server
I have an express app with a few endpoints and am currently testing it using mocha, chai, and chai-http. This was working fine until I added logic for a pooled mongo connection, and started building endpoints that depended on a DB connection. Basically, before I import my API routes and start the app, I want to make sure I'm connected to mongo.
My problem is that I'm having trouble understanding how I can export my app for chai-http but also make sure there is a DB connection before testing any endpoints.
Here, I am connecting to mongo, then in a callback applying my API and starting the app. The problem with this example is that my tests will start before a connection to the database is made, and before any endpoints are defined. I could move app.listen and api(app) outside of the MongoPool.connect() callback, but then I still have the problem of there being no DB connection when tests are running, so my endpoints will fail.
server.js
import express from 'express';
import api from './api';
import MongoPool from './lib/MongoPool';
let app = express();
let port = process.env.PORT || 3000;
MongoPool.connect((err, success) => {
if (err) throw err;
if (success) {
console.log("Connected to db.")
// apply express router endpoints to app
api(app);
app.listen(port, () => {
console.log(`App listening on port ${port}`);
})
} else {
throw "Couldnt connect to db";
}
})
export default app;
How can I test my endpoints using chai-http while making sure there is a pooled connection before tests are actually executed? It feels dirty writing my application in a way that conforms to the tests I'm using. Is this a design problem with my pool implementation? Is there a better way to test my endpoints with chai-http?
Here is the test I'm running
test.js
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../server').default;;
let should = chai.should();
chai.use(chaiHttp);
//Our parent block
describe('Forecast', () => {
/*
* Test the /GET route
*/
describe('/GET forecast', () => {
it('it should GET the forecast', (done) => {
chai.request(server)
.get('/api/forecast?type=grid&lat=39.2667&long=-81.5615')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
});
And this is the endpoint I'm testing
/api/forecast.js
import express from 'express';
import MongoPool from '../lib/MongoPool';
let router = express.Router();
let db = MongoPool.db();
router.get('/forecast', (req, res) => {
// do something with DB here
})
export default router;
Thank you for any help
After receiving some good feedback, I found this solution works best for me, based on Gomzy's answer and Vikash Singh's answer.
In server.js I'm connecting to the mongo pool, then emitting the 'ready' event on the express app. Then in the test, I can use before() to wait for 'ready' event to be emitted on the app. Once that happens, I'm good to start executing the test.
server.js
import express from 'express';
import bodyParser from 'body-parser';
import MongoPool from './lib/MongoPool';
let app = express();
let port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
(async () => {
await MongoPool.connect();
console.log("Connected to db.");
require('./api').default(app);
app.listen(port, () => {
console.log(`Listening on port ${port}.`)
app.emit("ready");
});
})();
export default app;
test.js
//Require the dev-dependencies
import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../src/server';
let should = chai.should();
chai.use(chaiHttp);
before(done => {
server.on("ready", () => {
done();
})
})
describe('Forecast', () => {
describe('/GET forecast', () => {
it('it should GET the forecast', (done) => {
chai.request(server)
.get('/api/forecast?type=grid&lat=39.2667&long=-81.5615')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
});
Express app is an instance of EventEmitter so we can easily subscribe to events. i.e app can listen for the 'ready' event.
Your server.js file will look like below,
import express from 'express';
import api from './api';
import MongoPool from './lib/MongoPool';
let app = express();
let port = process.env.PORT || 3000;
app.on('ready', function() {
app.listen(3000, function() {
console.log('app is ready');
});
});
MongoPool.connect((err, success) => {
if (err) throw err;
if (success) {
console.log('Connected to db.');
// apply express router endpoints to app
api(app);
// All OK - fire (emit) a ready event.
app.emit('ready');
} else {
throw 'Couldnt connect to db';
}
});
export default app;
Just create a function below to connect to mongo and, make it returns a promise.
then use await to wait for it to connect and return. the function could be like that
function dbconnect(){
return new Promise(function(resolve, reject){
MongoPool.connect((err, success) => {
if (err) reject(err);
if (success) {
resolve({'status' : true})
} else {
reject(new Error({'status' : false}))
}
})
})
}
And then, use
await dbconnect();
api(app);
app.listen(port, () => {
console.log(`App listening on port ${port}`);
})
now await line will wait for the function to connect to DB and then return success or error in case of failure.
This is a kind of solution you can use, but I would not recommend you to do this, what we actually do is.
create services and use those services in routes, don't write DB code directly in routes.
and
while writing tests for routes mock/stub those services, and test services separately in other test cases, where you just pass DB object and service will add functions on that DB objects, so in tests you can connect to DB and pass that object to those services to test functions, it will give you additional benefit, if you want to use dummy/test DB for testing you can set that in test cases.
Use Before function in your tests like below :
describe('Forecast', () => {
before(function(done){
checkMongoPool(done); // this function should wait and ensure mongo connection is established.
});
it('/GET forecast', function(cb){
// write test code here ...
});
});
And you can check mongodb connection like this below methods:
Method 1: just check the readyState property -
mongoose.connection.readyState == 0; // not connected
mongoose.connection.readyState == 1; // connected`
Method 2: use events
mongoose.connection.on('connected', function(){});
mongoose.connection.on('error', function(){});
mongoose.connection.on('disconnected', function(){});
You can use running server instead of a express instance.
Start your server with a private port, then take tests on the running server.
ex: PORT=9876 node server.js
In your test block, use chai.request('http://localhost:9876') (replace with your protocol, server ip...) instead of chai.request(server).
If you're using native mongodb client you could implement reusable pool like:
MongoPool.js
// This creates a pool with default size of 5
// This gives client; You can add few lines to get db if you wish
// connection is a promise
let connection;
module.exports.getConnection = () => {
connection = MongoClient(url).connect()
}
module.exports.getClient = () => connection
Now in your test you could,
const { getConnection } = require('./MongoPool')
...
describe('Forecast', () => {
// get client connection
getConnection()
...
In your route:
...
const { getClient } = require('./MongoPool')
router.get('/forecast', (req, res) => {
// if you made sure you called getConnection() elsewhere in your code, client is a promise (which resolves to mongodb connection pool)
const client = getClient()
// do something with DB here
// then you could do something like client.db('db-name').then(//more).catch()
})