How to handle file upload using express router? - javascript

Here are my server-side index.js:
import Express from 'express';
import fileUpload from 'express-fileupload';
import http from 'http';
import TestRouter from "./TestRouter.js";
let app = new Express();
let httpServer = http.createServer(app);
app.use(Express.json());
app.use(fileUpload({debug:true}));
app.post('/test/uploadFile',async (req, res, next) => {
console.log(req.body);
Object.keys(req.files).forEach(key=>{
console.log("Name:"+req.files[key].name);
console.log("MIMETYPE:"+req.files[key].mimetype);
console.log("File size:"+req.files[key].size);
console.log("==================================");
});
res.status(200).end();
});
let portNo=8080;
httpServer.listen(portNo, () => {
console.log('Express server is running on localhost:'+portNo);
})
It works fine.
When I change the code to :
import Express from 'express';
import fileUpload from 'express-fileupload';
import http from 'http';
import TestRouter from "./TestRouter.js";
let app = new Express();
let httpServer = http.createServer(app);
app.use(Express.json());
app.use(fileUpload({debug:true}));
app.use('/test', TestRouter);
let portNo=8080;
httpServer.listen(portNo, () => {
console.log('Express server is running on localhost:'+portNo);
})
And the TestRouter.js source code is below:
import Express from 'express';
let wrapper = function () {
const router = Express.Router();
router.post('/:action', async (req, res, next) => {
console.log(req.params.action);
switch (req.params.action) {
case "uploadFile":
console.log("hi");
res.status(200).end();
break
default:
next();
break
}
});
return router;
}
export default wrapper;
I find that the TestRouter does not be triggered.
Why?

Finally, I get it working by replacing the following statement:
app.use('/test', TestRouter);
with
app.use('/test', TestRouter());

Related

when run index.js DB work when run server.js DB not work

I have three files when I try running index.js file DB work well but router does not work and if run server.js DB and router does not work
server
import express from 'express'
import cors from 'cors'
import restaurants from './api/restaurants.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/restaurants", restaurants)
app.use("*", (req, res) => res.status(404).json({error: "Not Found"})) // any router not found in our routers
export default app;
index
import app from './server.js'
import mongodb from 'mongodb'
import dotenv from 'dotenv'
dotenv.config()
const mongoClient = mongodb.MongoClient
const port = process.env.PORT || 8000
mongoClient.connect(
process.env.RESTREVIEWS_DB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
).catch((e) => {
console.log(e.stack)
process.exit(1)
}).then(async client => {
app.listen(port, () => {
console.log(`app listen in link http://localhost:${port}/api/v1/restaurants`)
})
})
router
import express from 'express'
const router = express.Router();
router.get('/api/v1/restaurants', (req, res) => {
res.status(200).send("HelloWorld");
})
export default router

Dynamic import is not working on express routes

I'm trying to implement a dynamic import inside a express.js router
now I have a bellow code
HelloWorldController.js
export const helloWorld = function (req, res) {
res.send('hello world')
}
router.js
export default async function (app) {
app.use('/', await ( async function () {
const helloWorldController = await import('./helloWorldController.js')
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
server.js
import express from 'express'
import router from './router.js'
const app = express()
router(app)
app.listen(3000, function(){
logger.ready(`Web Server is running on port 3000`)
})
This is the result I'm getting when I run server.js
I have a 404 error
GET / 404 18.761 ms - 25
This is working fine
router.js
import * as helloWorldController './helloWorldController.js'
export default async function (app) {
app.use('/', await ( async function () {
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
** What am I doing wrong? **
ES6 import syntax is not supported yet in node js,
try this syntax const {express} = require("express")

Nodejs Express simple import js file router

how to import the user.json json file into my user.js ? when i type / user the json should be displayed? new version of node I don't understand
index.js
import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
app.use('/users', usersRoutes);
app.get('/', (req, res) => {
res.send('hello');
});
app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));
user.js
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send();
});
export default router;
import express from 'express';
import userJSON from '../user.json' // < ------- here
const router = express.Router();
router.get('/', (res, req) => {
res.send();
});
export default router;
Depending of the version you are using you either has to use babel or include the --experimental-json-modules flag for the module to work. ** node v.14 does not need anything.
node --experimental-json-modules about.js
import express from 'express';
import userfile from '../user.json' // import the json file
const router = express.Router();
router.get('/', (res, req) => {
res.send(userfile); //this line sends the json
});
export default router;
Instead use the fs module:
const user = require('fs').readFileSync('../user.json', 'utf-8');
You can do it by simply:
import express from 'express';
import user from '../user'; // <---- Don't need even the .json extension.
const router = express.Router();
router.get('/', (res, req) => {
res.send(user);
});
export default router;

TypeError: Cannot read property 'use' of undefined Express

I'm facing some issues with my express server when I use the 'app.use' command
in my task-routes.js file, I have the following code
import express from 'express';
const router = express.Router();
router.post('/task',(req, res) => {
res.send('post.task - create a task');
});
router.get('/task',(req, res) => {
res.send('get.task - get all tasks')
});
router.get('/task/:id',(req, res) => {
res.send('get.task/:id - get task by id')
});
router.put('/task',(req, res) => {
res.send('put.task - update a task')
});
router.delete('/task',(req, res) => {
res.send('delete.task - delete a task')
});
export default router;
And in my routes.js file, I have this
import taskRoutes from './api/task/tasks-routes';
export function registerRoutes(app) {
app.use('/api',taskRoutes);
}
Index.js
import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes();
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))
This is the error I keep getting
/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15
app.use('/api', _tasksRoutes2.default);
^
TypeError: Cannot read property 'use' of undefined
at registerRoutes (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15:7)
at Object.<anonymous> (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/index.js:14:28)
You are missing to pass app as argument at Index.js
import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes(app); // <- Here
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))
app.use('/api',taskRoutes);
So you call app.use
What is app?
export function registerRoutes(app) {
It is the first argument you pass to registerRoutes.
So what is that?
registerRoutes();
There isn't one. You didn't pass it an argument.
You have to pass the express object as the argument when you call the function.

Typescript resulting in cannot find module error

I am trying to build a basic Express api and am running in to an odd module not found error. Before introducing TypeScript to my project, I never got this error. This has been quite frustrating to resolve. I appreciate any suggestions on why I am getting this error and how to resolve.
server.ts
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
//import * as api from "api"; also tried this
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api', require('./api'));
app.use('*', (req, res, next) => {
let error = new Error('404: not found');
next(error);
});
app.use((error, req, res, next) => {
res.status(500).send({
error: {
message: error.message
}
});
});
const port = 3000;
app.listen(port, () => {
console.log('listening on port', port);
});
module.exports = app;
api/api.ts
import express from "express";
const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
module.exports = router;
With typescript, we don't use module.exports but export directly like so:
import express from "express";
export const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
Then we can get the router with
import {router} from './api'

Categories