I am trying to follow along a tutorial and use nodejs with 'gridfs-stream' along with a react front end. The tutorial is from last year in 2020.
Here is my code.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const path = require('path');
const Pusher = require('pusher')
const mongoPosts = require ('./mongoPosts.js')
// const currentTournamentControllers = require('../controllers/currenttournament-controllers');
const app = express();
const port = process.env.PORT || 9000
app.use(bodyParser.json())
app.use(cors())
const mongoURI = 'mongodb+srv://fbclient:rmbmbkvZVHw3e6OK#cluster0.emaw1.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const conn = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI)
mongoose.connection.once('open', () => {
console.log('DB Connected')
})
let gfs
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('images');
});
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {{
const filename = `image-${Date.now()}${path.extname(file.originalname)}`
const fileInfo = {
filename: filename,
bucketName: 'images'
}
resolve (fileInfo)
}})
}
})
const upload = multer({storage})
app.get('/', (req, res) => res.status(200).send('hello world'))
app.post('/upload/image', upload.single('file'), (req, res) => {
res.status(201).send(req.file)
})
app.post('/upload/post', (req, res) => {
const dbPost = req.body
console.log(dbPost)
mongoPosts.create(dbPost, (err, data) => {
if(err){
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get('/retrieve/image/single', (req, res) => {
console.log(req.query.name)
gfs.files.findOne({filename: req.query.name}, (err, file) => {
if(err) {
res.status(500).send(err)
} else {
console.log(file)
if(!file || file.length === 0) {
console.log("hi i errored out")
res.status(404).json({err: 'file not found'})
} else {
console.log("hi i am trying to read")
const readstream = gfs.createReadStream(file.filename)
readstream.pipe(res)
}
}
})
})
app.get('/retrieve/posts', (req, res) => {
mongoPosts.find((err, data) => {
if(err){
res.status(500).send(err)
} else {
data.sort((b,a) => {
return a.timestamp - b.timestamp
})
res.status(200).send(data)
}
})
})
app.listen(port, () => console.log(`listening on localhost:${port}`))
The problem is with readstream. When I am trying to retrieve the data it shows the error
TypeError: grid.mongo.ObjectID is not a constructor
I did some debugging and figured out that this can be fixed by changing a value inside the gridfs.js file in the node_modules. The change being suggested on Stack Overflow was this :-
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
changed to
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectId(), this.name, this.mode, options);
The suggestion was to change the grid.mongo.ObjectID value to grid.mongo.ObjectId. So I did that. Now the error coming out is as follows:-
TypeError: grid.mongo.GridStore is not a constructor
For this I am not getting any fixes on stack overflow or any other websites. Can someone please help
Related
While saving data to MongoDB, the characters that generated from a text area isn't generates correctly within the database, the output is just none (''), I've tried to change the input's unicode but nothing appeared to work. I will appreciate your help to let me know what I did wrong - and of course I will learn from it ;)
My whole JS' code
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var http = require('http').Server(app)
var io = require('socket.io')(http)
var mongoose = require('mongoose')
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
mongoose.Promise = Promise
var dbUrl = 'mongodb+srv://username:1234#cluster0.iwdr9.mongodb.net/database'
var Message = mongoose.model('Message', {
name: String,
message: String
})
app.get('/messages', (req, res) => {
Message.find({}, (err, messages) => {
res.send(messages)
})
})
app.get('/messages/:user', (req, res) => {
var user = req.params.user
Message.find({name: user}, (err, messages) => {
res.send(messages)
})
})
app.post('/messages', async (req, res) => {
try {
var message = new Message(req.body)
var savedMessage = await message.save()
console.log('saved')
var censored = await Message.findOne({ message: 'badword' })
if (censored)
await Message.remove({ _id: censored.id })
else
io.emit('message', req.body)
res.sendStatus(200)
} catch (error) {
res.sendStatus(500)
return console.error(error)
} finally {
console.log('message post called')
}
})
mongoose.connect(dbUrl, { useMongoClient: true }, (err) => {
console.log('MongoDB status is', err)
})
I am trying to upload a file and save it to a mongoose database. however, i keep getting an error
this is the error
this is the code i am using
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const uuid = require('uuid').v4;
const FileSchema = require('../models/files');
const crypto = require('crypto');
//Set Storage Engine
const storage = multer.diskStorage({
destination: (req, response, callback) => {
callback(null, './public/uploads/');
},
filename: (request, file, callback) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (error, buf) => {
if(error){
return reject(error);
}
const ext = path.extname(file.originalname);
const id = uuid();
const filePath = `files/${id}${ext}`;
FileSchema.create(filePath)
.then(() => {
callback(null, filePath);
});
});
});
}
});
//init upload
const upload = multer({storage: storage});
router.post('/uploads', upload.array('files'),(req, response) => {
return response.json({ status: 'OK', uploaded: req.files.length});
});
module.exports = router;
please can anyone help?
thank you.
I am reading a file and looking for changes in it in real time using fs.watch which is working correctly. Now I want to make a call to app.get every time my file gets changed. But my function "func_read_file_lines" is still sending the old file to back. I can't find the problem.
const express = require('express')
const app = express()
app.set('view engine', 'ejs');
var fs = require('fs');
const request = require('request');
require('log-timestamp');
path = require("path");
var filename = path.resolve('test.txt');
const buttonPressesLogFile = filename;
fs.watch(buttonPressesLogFile, (event, filename) => {
if (filename && event === 'change') {
console.log(`${filename} file Changed`);
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
console.log(last_n_lines)
}).catch((err) => {
console.log(err)
})
}
});
let func_read_file_lines = new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', function read(err, data) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(data)
}
});
})
app.get('/', (req, res) => {
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
res.render('display', {
last_n_lines: last_n_lines
});
}).catch((err) => {
console.log(err)
})
})
const port = 3000
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
It's because you only create func_read_file_lines once. Try creating a function to return the promise like so:
const express = require('express')
const app = express()
app.set('view engine', 'ejs');
var fs = require('fs');
const request = require('request');
require('log-timestamp');
path = require("path");
var filename = path.resolve('test.txt');
const buttonPressesLogFile = filename;
fs.watch(buttonPressesLogFile, (event, filename) => {
if (filename && event === 'change') {
console.log(`${filename} file Changed`);
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
console.log(last_n_lines)
}).catch((err) => {
console.log(err)
})
}
});
// CHANGE THE LINE BELOW
let func_read_file_lines = () => new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', function read(err, data) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(data)
}
});
})
app.get('/', (req, res) => {
func_read_file_lines(). // CHANGED THIS LINE
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
res.render('display', {
last_n_lines: last_n_lines
});
}).catch((err) => {
console.log(err)
})
})
const port = 3000
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I am creating a sveltejs/sapper app. I am trying to post some info from the frontend to the backend express server using axios in the script tag. Although get requests from external sources are succeeding, axios is throwing a 404 error while posting to the express route. Refer these images posted below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
import sirv from 'sirv';
import * as sapper from '#sapper/server';
const app = express();
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
app.use(
sirv('static', {dev}),
sapper.middleware(),
bodyParser.json(),
bodyParser.urlencoded({extended:true})
);
app.post('/task', (req, res) => {
res.sendStatus(200);
console.log(req.body);
// fs.writeFile(`./downloads/${req.body.file}`, req.body.buffer, (err) => {
// if (err) throw err;
// console.log(`${res.file} downloaded to backend server`);
// });
});
app.listen(PORT, err => {
if (err) console.log('error', err);
});
frontend script
<script>
//variables
let start = false;
let url = '';
let filename = '';
let downloadProgress = 0;
let error = false;
let progressBarStyle = 'bg-success';
//automated Events
$:downloadLabel = downloadProgress.toString();
$:if(downloadLabel == '100') {
progressBarStyle = 'bg-warning';
downloadLabel = 'DOWNLOAD COMPLETE! FILE WILL BE TRANSFERED SHORTLY!';
}
//axios config
let config = {
onDownloadProgress: progressEvent => {
downloadProgress = Math.floor((progressEvent.loaded * 100) / progressEvent.total); }
}
//functions
function startDownload() {
start = true;
axios.get(url, config).then((res) => {
if(res.status == 200) {
let data = {
file: filename,
buffer: res.data
}
axios.post('/task', data).then(() => {
console.log('Data sent to server');
}).catch((err) => {
console.log(err);
});
}
else {
error = true;
}
}).catch((err) => {
error = true;
});
}
function reset() {
// start = false;
// url = '';
// filename = '';
// downloadProgress = 0;
window.location.reload();
}
</script>
browser console
network tab
You use sapper,
Try to read docs.
example:
const express = require('express');
import sirv from 'sirv';
import compression from 'compression';
import * as sapper from '#sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = express();
app
/* add your handlers here */
.post('/task', (req, res, next) => {
res.sendStatus(200);
console.log(req.body);
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
I find here solution
You have to send something in the request handler:
(req, res) => {
res.sendStatus(200);
}
I have a working codebase where they have already setup node proxy and jwt.
my server is running at 1010 port
but when I hit this url http://localhost:1010/sampletest
I am getting an error in the browser screen Cannot GET /sampletest
even I hit this url http://localhost:1010/jump/api/v1 but still I am getting same error
can you tell me how to fix it or am I missing anthing in the configurations
providing my index.js and server.js code below
sports.js
const express = require('express');
const axios = require('axios');
const mime = require('mime-types');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');
const AppConstants = require('../../../constants/AppConstants');
const credentials = require('../../../internals/credentials.json');
const memberGroupingHelper = require('../../helpers/rank/memberGrouping');
const exportHelper = require('../../helpers/rank/rankExportHelper');
const formatExportData = require('../../helpers/rank/formatExportData');
const rankCommonHelper = require('../../helpers/rank/rankCommonHelper');
const rankProvDataHelper = require('../../helpers/group/getProvData');
//const aggregateHelper = require('../../helpers/group/aggregateFilter');
const { rankAggregatelastrsApi } = require('jump-svc-utils');
//router.get('/:searchMode/:lastrSearch', (req, res, next) => {
router.get('/sampletest', (req, res, next) => {
const { originalUrl } = req;
//console.log(" originalUrl ", originalUrl);
const mode = req.params.searchMode;
const value = encodeURIComponent(req.params.lastrSearch);
console.log("document 40--->", mode);
console.log("for document Testing0--->", mode);
const url = `/jkjkjk/sdjksdjkjksdjksd/sdklsdlksdklsdkl`;
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
// var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
var jwtToken = `Bearer 787878bjhbnmnmmwqdqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqw`;
axios.get(url, { headers: { "Authorization": jwtToken } })
.then((response) => {
console.log("document then0--->", response);
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
res.set('Content-Type', fileType);
res.set('Content-disposition', `attachment; ${fileName}`);
res.send(file);
})
.catch((e) => {
console.log("e catch document0--->", e);
console.log("e.message catch document0--->", e.message);
console.log("catch document--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
ResponseUtil.callService(res, url);
});
module.exports = router;
index.js
const express = require('express')
const app = express()
const port = 1010
const jumpServices = require('./services/jump');
const compression = require('compression');
var BodyParser = require('body-parser');
const glob = require('glob');
const path = require('path');
app.use('/jump/api/v1', jumpServices);
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
//app.use(compress())
// app.use(compression());
// include all the controllers
const controllers = glob.sync(path.join(__dirname, '/controllers/**/*.js'));
console.log("controllers--->", controllers);
controllers.forEach((controllerFileName) => {
require(controllerFileName)(app); //eslint-disable-line
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
I don't see any calls registering your sub Routers with the top level express application. You should need to call app.use for each of your sub routers.