How can I solve this : Cannot Get /upload error - javascript

I cloaned this code on youtube, it has Cannot GET /upload error.
I search google about this error, and many say it looks like app.get('/upload') missing problem.
But I don't know how to fix this code.
Can you tell me how to fix it?
const ipfsClient = require('ipfs-http-client');
const express = require('express');
const bodyParser = require('body-parser');
const fileupload = require('express-fileupload');
const fs = require('fs');
const ipfs = new ipfsClient(
{host:'localhost',
port:'5001',
protocol:'http'
});
const app = express();
app.engine('ejs',require('ejs').__express);
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(fileupload());
app.get('/',(req,res)=>{
res.render('home');
});
**app.post('/upload', (req,res)=>{
const file = req.files.file;
const fileName = req.body.fileName;
const filePath = 'files/' + fileName;
file.mv(filePath, async(err) => {
if (err){
console.log('Error failed to download the file');
return res.status(500).send(err);
}
const fileHash = await addFile(fileName, filePath);
fs.unlink(filePath, (err)=>{
if(err) console.log(err);
});
res.send(fileHash);
});
});**
*const addFile = async(fileName, filePath) =>{
const file = fs.readFileSync(filePath);
const fileAdded = await ipfs.add({path:fileName,content:file});
const fileHash = fileAdded[0].hash;
return fileHash;
};*

Since the /upload route is specified for POST method:
app.post('/upload', (req,res)=>{
there is no GET /upload route, which is the error you're getting.
So when calling your endpoint, you should change the method to POST

Related

TypeError: app.use() requires a middleware function No clue why error

so I am getting the the error : TypeError: app.use() requires a middleware function.
I am unsure why i made sure i exported the file, but I am a bit confused why. I think i linked it up correctly in my server file as well.
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const app = express()
const bodyParser = require('body-parser')
app.use(morgan('dev'))
require('dotenv').config()
const { expressjwt: jwt } = require("express-jwt")
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27017/recipe', ()=> console.log('connected to database'))
app.use('/auth', require('./routes/authRouter'))
app.use("/api", jwt( {secret: process.env.SECRET, algorithms: ['HS256']}))
app.use('/api/recipe/', require('./routes/recipeRoutes'))
app.use('/api/public/'), require('./routes/publicDelete')
app.use('/api/comments/', require('./routes/commentRouter'))
app.use('/api/ingredients/', require('./routes/ingredRouter'))
app.use((err,req,res,next)=>{
console.log(err)
if(err.name ==='UnauthorizedError'){
res.status(err.status)
}
return res.send({message:err.message})
})
app.listen(8000, ()=>{
console.log('hello ')
})
const express = require('express')
const publicDeleteRouter = express.Router()
const Recipe = require('../models/recipe')
const User = require('../models/user')
publicDeleteRouter.delete('/:recipeId', (req, res, next) =>{
Recipe.findOneAndDelete({idMeal: req.params.recipeId, user: req.auth._id}, (err, deletedRecipe) => {
if(err){
console.log(idMeal)
res.status(404)
return next(err)
}
console.log('successfully deleted: ', deletedRecipe)
return res.status(200).send(`Successfully deleted ${deletedRecipe}`)
})
})
module.exports = publicDeleteRouter

Server not connect to mongoDB

I am having trouble connecting my server to MongoDb database using mongoose. The server will start and then crash while trying to connect to mongoDB. the error is getting caught in db.js and then exiting the program. It seems the server will connect to local host then end when it trys to connect to mongoDB.
ERROR!
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server is running on : http://localhost:8000
MongoDB is not connected
[nodemon] app crashed - waiting for file changes before starting...
here Is my db.js I have linked it to my sever.js file
const mongoose = require('mongoose')
const connectDB = async()=>{
try{
await mongoose.connect("mongodb+srv://jj-test:jj#videos.cdstjfw.mongodb.net/?retryWrites=true&w=majority")
console.log("MongoDB is connected!")
}catch(err){
console.log("MongoDB is not connected")
console.error()
process.exit(1)
}
}
module.exports=connectDB
server.js
const express = require("express");
const cors = require("cors");
const dotenv = require('dotenv');
const mongoose = require('mongoose')
const crypto = require('crypto')
const path = require('path')
const GridFsStorage = require('multer-gridfs-storage')
const multer = require('multer')
const Grid = require('gridfs-stream')
const connectDB= require('./services/db')
const PORT = process.env.PORT || 8000;
const app = express();
const init = async ()=>{
app.use(express.json());
app.use(express.urlencoded({ extended: false }))
app.use(cors());
await connectDB()
const conn = mongoose.connection
const gfs = await Grid(conn.db,mongoose.mongo)
gfs.collection('media')
// storage location using muster
const storage = await new GridFsStorage({
db: conn.db,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename =
buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename,
bucketName: 'media'
};
return resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// uploading a file route
app.post('/upload',upload.single('file'),(req,res)=>{
res.json(req.file)
})
// media bucket route
app.get('/files',async(req,res)=>{
try{
const files =await gfs.files.find().toArray()
res.json(files)
}catch(err){
res.status(400).send(err)
}
})
// route for streaming a file
app.get('/read/:filename',async(req,res)=>{
const{filename}= req.params
try{
const readstream = await gfs.createReadStream({filename})
readstream.pipe(res)
}catch(err){
res.status(400).send(err)
}
})
app.delete('/delete/:filename',async(req,res)=>{
const{filename}=req.params
try{
await gfs.files.remove({filename})
res.status(200).end()
}catch(err){
res.status(400).send(err)
}
})
}
init()
app.listen(PORT, () => {
console.log(`Server is running on : http://localhost:${PORT}`);
});
Also worthwhile adding console.log(err) to help give more descriptive error info on the server.js file
You need add database name:
mongoose.connect("mongodb+srv://jj-test:jj#videos.cdstjfw.mongodb.net/DATABASEname?retryWrites=true&w=majority")

Uploading an image, frontend and backend

const { timeStamp, time } = require('console');
const express = require('express');
const fileUpload = require('express-fileupload');
const path = require("path");
const util = require('util');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/images', express.static(__dirname + 'public/images'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(express.static("./public"));
app.post("/upload", async (req, res) => {
try {
// File name, size and type values
const file = req.files.file;
const fileName = file.name;
const size = file.data.length;
const extension = path.extname(fileName);
const name = file;
// Allowed filetypes
const allowedExtensions = /png|jpg|dds|ico|mov|mp4|flv|avchd|avi|webm|mp3|aac|wav|flac|svg|webp|gif|bmp|tiff|psd|psb|blend|fbx|obj|raw|aep|prel|prproj|ai/;
// Mazimun file Size
if (!allowedExtensions.test(extension)) throw "Filetype not allowed"
if (size > 200000000) throw "File must be less than 200MB"
// Uploaded file name
const md5 = file.md5;
const URL = "/uploads/" + fileName + Date.now() + extension;
await util.promisify(file.mv)("./public" + URL);
// Errors and Success messages
res.json ({
message: "File uploaded successfully!",
url: URL,
})
} catch(err){
console.log(err);
res.status(500).json({
message: err,
})
}
})
app.listen(port, () => console.info(`Listening on port ${port}`))
So I have this script for uploading images to a folder in my public folder in the root directory of my website, I'm a real noob when it comes to js so, I was wondering how do I implement a button that let's the user select a file as well as a submit button and maybe perhaps a couple of text fields where the user can add info about the file in the frontend so it works in the backend?
Because I have no idea of how to make the frontend and backend work together in such a way.
Thanks for any help

File upload makes Node JS unresponsive with Multer

I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.
Whats the best way to tackle this ?
In your sample code, you must just send a response to the client by res.json() or res.end() :
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
res.status(204).end();
});
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
res.status(204).end();
});
i can give you an example of how i implemented an imageupload in my app. it the code to upload a profile image for a user. i am also using multer middleware so it shoulder be similiar for you:
code is as follows:
// multer middleware:
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
};
module.exports = storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error('invalid mime type');
if (isValid) {
error = null;
}
cb(error, 'images');
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
if (name.includes('.' + ext)) {
cb(null, name)
} else {
cb(null, name + '.' + ext);
}
},
});
and here the code in the service handling the fileupload
// profile service in backend written in express
exports.uploadImage = (req, res, next) => {
const url = req.protocol + '://' + req.get('host');
profileRepository
.findOne({ _id: req.params.id })
.then((response) => {
const fetchedUser = response;
fetchedUser.imagePath = url + '/images/' + req.file.filename;
profileRepository
.updateOne({ _id: req.params.id }, fetchedUser)
.then((response) => {
return res.status(200).json({
message: 'profileimage updated',
});
})
.catch((error) => {
return res.status(500).json({
message: 'uploading image failed',
});
});
})
.catch((error) => {
return res.status(404).json({
message: 'fetching user failed',
});
});
};
then i use the middleware in my profile routes file like this:
// profile.routes.js
const express = require('express');
const ProfileController = require('./profileController');
const checkAuth = require('../middleware/checkAuth');
const router = express.Router();
const fileStorage = require('../middleware/fileStorage');
const multer = require('multer');
// imageUpload
router.post('/user/image/:id', checkAuth, multer({storage: fileStorage}).single('image'), ProfileController.image);
my Controller then calls the service function with the actual business logic like this:
// profile.controller.js
const profileService = require('./profileService');
exports.image = (req, res, next) => {
return profileService.uploadImage(req, res);
};
and finally my route is used by my app.js file like this:
// app.js
const express = require('express');
const profileRoutes = require('./profile/profileRoutes');
const app = express();
// set images path for saving images on server
app.use('/images', express.static(path.join('images')));
app.use('/api', profileRoutes);
module.exports = app;
i hope i was able to point you in the right direction with my example

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Why does the bodyParser not working?

This is my index.js file and i think i have placed the routes after installing bodyParser but still getting the syntax error.
const express = require('express'); //Framework to build server side application
const morgan = require('morgan'); //Logging the nodejs requests
const bodyParser = require('body-parser'); //To get the JSON data
const urls = require('./db/urls');
const app = express();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public')); //If a request comes with '/' check if file is in there if it is then serve it up.
// app.get('/', (req, res) => {
// res.send('Hello, World !!');
// });
app.post('/api/shorty', async (req, res) => {
console.log(req.body);
try {
const url = await urls.create(req.body); //Passing the body data which is JSON to create function
res.json(url);
} catch (error) {
res.status(500);
res.json(error)
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
This is the urls.js file,I am not getting where have i messed up to make Syntax.JSON error in this file.
const db = require('./connection');
const Joi = require('joi');//Schema validation
const urls = db.get('urls');
const schema = Joi.object().keys({
name : Joi.string().token().min(1).max(100).required(),
url : Joi.string().uri({
scheme: [
/https?/ //get http 's' is optional
]
}).required()
}).with('name','url');
//almostShorty = {
// name = ,
// url =
// }
function create(almostShorty){
const result = Joi.validate(almostShorty, schema);
if(result.error === null){
return urls.insert(almostShorty);//Inserting the object in the Data Base.
}else{
return Promise.reject(result.error);
}
};
module.exports = {create};//Exporting the create function.

Categories

Resources