Importing express router from es6 module - javascript

this is my first nodeJS project and im getting stuck already. In the package.json "type" = "module".
I keep getting an error "ERR_MODULE_NOT_FOUND".
I tried default and named export but both didnt work.
productRoutes.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
res.status(200).json({ msg: 'get products' });
});
export default router;
server.js
import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import routes from './api/v1/routes/productRoutes';
// express app
const app = express();
// middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log(req.path, req.method);
next();
});
// routes
app.use('/api/products', routes);
// connect to db
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('connected to database');
// listen to port
app.listen(process.env.PORT, () => {
console.log('listening for requests on port', process.env.PORT);
});
})
.catch((err) => {
console.log(err);
});

If you don't provide extension of a js file .js the node compiler doesn't understand it, unless you use some other transpilers like babel.
so change
import routes from './api/v1/routes/productRoutes';
to
import routes from './api/v1/routes/productRoutes.js';

Related

express.use in firebase functions

I have finished Nodejs express app and I want to deploy it to Firebase functions when I run firebase emulator.
I am not able to reach my app.use routes.
I am able to reach
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
This is my index.js in functions
import functions from 'firebase-functions';
import app from '../app.js';
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
export const invest = functions.https.onRequest(app);
my app.js
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import mongoSanitize from 'express-mongo-sanitize';
import xss from 'xss-clean';
import hpp from 'hpp';
import path from 'path'
import AppError from './utils/appError.js';
import companyRouter from './routs/company.js'
import userRouter from './routs/user.js'
const app = express();
app.use(cors());
// 1) GLOBAL MIDDLEWARES
// Set security HTTP headers
app.use(helmet());
// Development logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(bodyParser({
// json: { limit: '50mb', extended: true },
// urlencoded: { limit: '50mb', extended: true }
// }));
// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!'
});
app.use('/api', limiter);
// Body parser, reading data from body into req.body
app.use(express.json({ limit: '250kb' }));
// Data sanitization against NoSQL query injection
app.use(mongoSanitize());
// Data sanitization against XSS
app.use(xss());
// Prevent parameter pollution
app.use(
hpp({
whitelist: []
})
);
// Serving static files
// app.use(express.static(`${__dirname}/public`));
// Test middleware
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
// console.log(req.headers);
next();
});
// app.use(express.static(path.resolve('../client/build')));
// app.get('*', (req, res) => {
// res.sendFile(path.resolve('../client/build', 'index.html'));
// });
// // 3) ROUTES
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
// app.use('/api/v1/reviews', reviewRouter);
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
// app.use(globalErrorHandler);
export default app;
My router
company.js
import express from 'express';
import {getAllCompanies, getOneCompany, createCompany, updateCompany, deleteCompany, likeCompany, newPrice, GetAllPrices} from '../controllers/company.js'
import { protect } from '../controllers/auth.js'
import { createNews, getAllNews } from '../controllers/newsController.js';
const router = express.Router();
router.get('/', getAllCompanies);
router.get('/ir', getAllNews);
router.get('/myAccount', GetAllPrices);
router.get('/:id', getOneCompany);
router.post('/', createCompany);
router.post('/myAccount', newPrice);
router.post('/ir', createNews);
router.patch('/:id/likeCompany',protect, likeCompany);
router.patch('/:id', updateCompany);
router.delete('/:id', deleteCompany)
export default router;
I get local address
http://localhost:5001/investfouyou/us-central1/invest
and that gets me
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
but I need to get
http://localhost:5001/investfouyou/us-central1/invest/api/v1/companies
to access my router
I want to get to these two lines
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
Please help

Connect-flash not worked when imported via ES6 module import

I'm trying to setup connect-flash for my nodejs express application. I'd like for a message to be flashed when a user goes to certain pages. I'm using ES6 package type module for this application. My code is below. No error is logged in console, but no flashed message appears upon going to my /privacy-policy route.
// Import modules
import express from 'express';
import path from 'path';
import ejsMate from 'ejs-mate';
import session from 'express-session';
import flash from 'connect-flash';
import methodOverride from 'method-override';
import { fileURLToPath } from 'url';
import mainRoute from './routes/main.js';
import contactRotues from './routes/contact.js';
// Setup path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Initialize app
const app = express();
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
// Setup session
const sessionConfig = {
secret: 'thisshouldbeabettersecret!',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(flash());
// Routes
app.use('/', mainRoute);
app.use('/contact', contactRotues)
app.get('/privacy-policy', (req, res) => {
req.flash('test message', 'success')
res.render('privacy')
});
app.get('/terms-of-service', (req, res) => {
res.render('terms')
});
app.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404))
})
app.use((err, req, res, next) => {
const { statusCode = 500 } = err;
if (!err.message) err.message = 'Oh No, Something Went Wrong!'
res.status(statusCode).render('error', { err })
})
app.listen(3000, () => {
console.log('Serving on port 3000')
})
Is there an error in how I'm importing connect-flash? How can I get connect-flash to work? I need to import it with ES6 import syntax rather than require syntax since my application is utilizing a necessary module that must be imported with ES6 module syntax.
If it's impossible to import connect-flash with ES6 import syntax, how else could I dynamically display a message to the user on a page they're redirected to?
Thank you.
You've imported it correctly. How do you plan to render the message?
I use 'express-messages' and add to code like this:
import messages from 'express-messages';
app.use((req, res, next) => {
res.locals.messages = messages(req, res);
next();
});
Then render using the ejs sample here https://www.npmjs.com/package/express-messages

Why do I have to call app.default.listen() in Express instead of app.listen()?

I am importing my Express app into a start script, which just listens on port 5000 locally.
I configured the Express app as follows:
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import helmet from 'helmet'
import router from '../../routes'
const restServer = express()
const middleWare = [
helmet(),
bodyParser.json(),
bodyParser.urlencoded({ extended: true }),
cors({
'Access-Control-Allow-Origin': '*',
allowedHeaders: 'Content-Type, Authorization',
methods: ['GET, POST, PUT, DELETE', 'OPTIONS']
})
]
restServer.use(...middleWare)
if (process.env.DEBUG === 'TRUE') {
const logger = require('morgan')
restServer.use(logger('dev'))
}
restServer.use('/api', router)
export default restServer
When I import this file into my start script, I tried to run
app.listen(5000, (err) => {
if (err) throw new Error()
console.log('successfully connected to port', PORT)
})
but it throws a TypeError: app.listen is not a function
It works when I call app.default.listen(5000)
I'm using Express 4.16.4

TypeError - Router.use() requires a middleware function but got a undefined

So am trying to create a RESTful api with express and nodejs. When i run npm start to start the server it throws an error saying Router.use() requires a middleware but got an undefined. Any ideas what could be the problew. My code is pasted below.
Thanks in advance
server.js
import express from 'express';
import bodyParser from 'body-parser';
import { router as Orders } from './routes/order';
const app = express();
// PORT Number
const PORT = process.env.PORT || '3000';
// Setting up the body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Setting up middleware for a specific route
app.use('/api', Orders);
app.listen(PORT, () => {
console.log(`Running application on port ${PORT}`);
});
order.js route
import express from 'express';
const router = express.Router();
router.get('/', (req, res, next) => {
res.send('Hello from api');
next();
});
export default router;
When using a default export:
export default router;
You should be importing it using the syntax:
import Orders from './routes/order'
Or, if you want to keep the import syntax the same, you can change the export so that it is not a default:
export { router }

node.js req.body undefined with express 4.16.X, body-Parser 1.X

I just starting to use node.js to build a RESTFul api. I'm now trying to insert data by post with json in body.
But when I try to get req.body always got undifined.
So I check at here. Saw some people said that the express configuration should before the route.
After I modified my code. I can't even get home page.
Can anyone help me solve this problem?
express.js before
/* express.js */
import bodyParser from 'body-parser';
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import config from './config';
import index from '../server/routes/index.route';
const app = express();
/* GET home page. */
app.get('/', (req, res) => {
res.send(`server started on port.. http://127.0.0.1:${config.port} (${config.env})`);
});
app.use('/api', index);
// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors);
// Http request logger
app.use(morgan('dev'));
export default app;
POST RESULT
{
"code": "ER_PARSE_ERROR",
"errno": 1064,
"sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "INSERT INTO Article SET ?"
}
express.js after
/* express.js */
/* ... */
const app = express();
// parse body params and attache them to req.body
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors);
// Http request logger
app.use(morgan('dev'));
/* GET home page. */
app.get('/', (req, res) => {
res.send(`server started on port.. http://127.0.0.1:${config.port} (${config.env})`);
});
app.use('/api', index);
export default app;
index.js
import config from './config/config';
import app from './config/express';
if (!module.parent) {
// listen on port config.port
app.listen(config.port, () => {
console.log(`index.js >>> server started on port http://127.0.0.1:${config.port} (${config.env})`);
});
}
export default app;
index.route.js
import express from 'express';
import mysql from 'mysql';
import article from './article.route';
import config from './../../config/config';
const router = express.Router();
/* GET localhost:[port]/api page. */
router.get('/', (req, res) => {
res.send(`此路徑是: localhost:${config.port}/api`);
});
/* mysql連線測試 */
router.get('/sqlTest', (req, res) => {
const connectionPool = mysql.createPool({
connectionLimit: 10,
host: config.mysqlHost,
user: config.mysqlUserName,
password: config.mysqlPass,
database: config.mysqlDatabase
});
connectionPool.getConnection((err, connection) => {
if (err) {
res.send(err);
console.log('連線失敗!');
} else {
res.send('連線成功!');
console.log(connection);
}
});
});
// article router
router.use('/article', article);
export default router;
article.route.js
const router = express.Router();
router.route('/').post(articleCtrl.articlePost);
article.controller.js
const articlePost = (req, res) => {
const insertValues = req.body;
console.log('insertValues ', insertValues);
articleModule.createArticle(insertValues).then((result) => {
res.send(result);
}).catch((err) => { return res.send(err); });
};
you need to call bodyParser.json and cors as a function; app.use(bodyParser.json());, app.cors()

Categories

Resources