bundle.js loads very slow - node.js

I am using ec2(nodejs+express+webpack)-cloudflare setup and my bundle size is only about 100kb.
But the problem is that the 100kb bundle takes way too long(25~30secs)
I think it is a problem in my express or nodejs setting since index.html[1kb] also takes 700ms and favicon[2kb] takes 1.91s to load.
I'm wondering if this is because ec2 freetier is slow or is it my setting that's keeping it so slow.
I use
1 cloudflare ssl for https connection
2 iptables prerouting from 80 to 3000(my node env)
3 express server with main page like this
const app = express();
const port = process.env.p || 3000;
app.get('/', function (request, response){
response.sendFile(path.resolve('public', 'index.html'), 'utf8');
});
app.use('/css', express.static('css'));
app.use('/static', express.static('static'));
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());
app.post('/signup', (req, res) =>{
signup(req.body, res);
});
app.post('/login', (req, res) =>{
login(req.body, res);
});
app.get('/userlist', (req, res)=>{
ulist(req.query, res);
});
app.get('/atoc', (req, res)=>{
console.log(req.query);
atocf(req.query, res);
});
app.get('/data/allshops', (req, res)=>{
allshops(res);
});
app.get('/manager/checkurl', (req,res)=>{
checkurl(req.query, res);
});
app.post('/manager/upload', upload.single('file'),(req,res)=>{
s3u(req.file,req.body, res);
})
app.post('/manager/addshop', (req,res)=>{
addshop(req.body, res);
});
app.post('/manager/editshop', (req,res)=>{
editshop(req.body, res);
});
app.post('/manager/shop', (req,res)=>{
mshopdata(req.body, res);
});
app.post('/manager/shops', (req,res)=>{
myshops(req.body, res);
});
app.post('/manager/pub', (req,res)=>{
msetpublic(req.body, res);
});
app.post('/manager/rm', (req,res)=>{
msetrm(req.body, res);
});
app.post('/data/shop', (req,res)=>{
if(req.body._url==undefined||req.body._url==''){
res.send("{'ic_error':'NO_URL'}");
}
else
shopdata(req.body, res);
});
app.get('*', function (request, response){
const paths = request.path.split('/');
if(nofollow.includes(paths[1])){
response.sendFile(path.resolve('public', 'index.html'), 'utf8');
return;
}
if(keypaths.includes(paths[1])){
response.sendFile(path.resolve('public', paths[1]+'.html'),'utf8');
return;
}
//shopmetadata({_url: decodeURIComponent(paths[1])}, response);
sendpage({_url: decodeURIComponent(paths[1])},response)
});
const server = app.listen(port, () => {
console.log('Express listening on port', port);
});
What may I be doing wrong that is slowing down the traffic so hard?
thanks in advance!

Related

express.js - basic application router not working

I just creating a basic app, but it seems not working for me. any one help me to find the mistake?
here is my code :
import express from "express";
const app = express();
const router = express.Router();
app.use((req, res, next) => {
console.log("first middleware");
next();
});
router.get("/a", (req, res, next) => {
res.send("Hello this is route a");
});
router.post("/c", (req, res, next) => {
res.send("Hello this is route c");
});
app.listen({ port: 8000 }, () => {
console.log("Express Node server has loaded");
});
Node version : v14.17.5
Express version : ^4.17.1
thanks in advance.
Use the router
import express from "express";
const app = express();
const router = express.Router();
router.get("/a", (req, res, next) => {
res.send("Hello this is route a");
});
router.post("/c", (req, res, next) => {
res.send("Hello this is route c");
});
app.use(router, (req, res, next) => {
console.log("first middleware");
next();
});
app.listen({ port: 8000 }, () => {
console.log("Express Node server has loaded");
});
You need the app to consume the router.
Try adding app.use('/route', router);
Use app.use
Example
app.use('/c', c);

Express middleware stuck in at the middle

I'm trying to using express().router as middleware for express server.
this is the code for the express server -
const server = express();
const port = process.env.PORT || 5000;
server.use(logger("short"));
server.use(respomnseTime(4)) // The number indicate how digits we want
server.use('/', mRouter);
server.use((request, response, next)=>{
mUtil.print("Request IP: " + request.url);
mUtil.print("Request Date: " + new Date());
next();
})
server.use((request, response, next)=>{
mUtil.auth(request, response, next);
})
server.use((request, response, next)=>{
console.log("Middleware 2");
next();
})
this is the code for the router (another file) -
const router = require('express').Router();
router.get('/', (request, response) => {
response.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED' });
});
router.get('/user/:username', (request, response)=>{
});
router.get('/about', (request, response)=>{
});
router.get('/contact', (request, response)=>{
});
It looks like he middlewares after -
server.use('/', mRouter);
not running. I thought the problem happens because there is no call to next() function, but I'm not sure how to write it. Anyone have an idea?
you should export your router like below
module.exports = router;

Express Middleware flow

Consider the following Express app:
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('\n\nALWAYS')
next()
})
app.get('/a', (req, res) => {
console.log('/a: route terminated')
res.send('/a')
})
app.use((req, res) => {
console.log('route not handled')
res.send('404 - not found')
})
app.listen(3000, () => {
console.log('listening on 3000')
})
Visit /a console result:
ALWAYS
/a: route terminated
ALWAYS
route not handled
Can somebody explain why is that there is another middleware log? I was expecting only 2 lines of console log. Instead
ALWAYS
route not handled
has been logged.
This is a very common point of confusion. The likely cause is that you went to /a in the browser and the browser made two requests. One for /favicon.ico and one for /a (that's what browsers do when you go to a new site they haven't previously cached the favicon for - the little glyph they display that represents the web site in some places in the browser).
If you log the request URL in your middleware and in your 404 handler, you will see the details of what is happening:
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('\n\nRequest for: ', req.url);
next();
})
app.get('/a', (req, res) => {
console.log('/a: route terminated')
res.send('/a')
})
app.use((req, res) => {
console.log('route not handled for ', req.url);
res.send('404 - not found');
});
app.listen(3000, () => {
console.log('listening on 3000')
})

Node js express res.json() return html not json

I have problem when a call router.get(), i am returning to response json using res.json() but it return html
here is my api.js
var express = require('express');
var router = express.Router();
var marklogic = require("marklogic");
var conn = require('../env.js').connection;
var db = marklogic.createDatabaseClient(conn);
router.route('/akt')
// Vraca usvojene akte
.get(function (req, res) {
res.json({message: 'TODO vraca usvojene akte'});
})
// Predlaganje akta
.post(function (req, res) {
db.documents.write(
{
uri: '/korisnik/1.xml',
contentType: 'application/xml',
collections: 'korisnik',
content: '<entry-list><entry id="horror2"></entry></entry-list>'
})
})
// Povlaci predlog akta
.delete(function (req, res) {
res.send({message: "TODO povlaci predlog akta"});
});
router.route('/amandman/:akd_id')
// Predlog amandmana na predlog akta
.post(function (req, res) {
res.send({message: 'TODO predlaganje amandmana na predlog akta'});
})
// Povlaci predlog amandmana
.delete(function (req, res) {
res.send({message: 'TODO povlaci predlog amandmana'});
});
module.exports = router;
Please can somebody tell me where is my error, also if you need some more file I will give it.
Edit:
I noticed when I remove from server.js this lines everything works, why is that?
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
Change this
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
})
to
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
})
You match every route to index.html when using * regular expression.

How can I get Express.js to 404 only on missing routes?

At the moment I have the following which sits below all my other routes:
app.get('*', function(req, res){
console.log('404ing');
res.render('404');
});
And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?
You just need to put it at the end of all route.
Take a look at the second example of Passing Route Control:
var express = require('express')
, app = express.createServer();
var users = [{ name: 'tj' }];
app.all('/user/:id/:op?', function(req, res, next){
req.user = users[req.params.id];
if (req.user) {
next();
} else {
next(new Error('cannot find user ' + req.params.id));
}
});
app.get('/user/:id', function(req, res){
res.send('viewing ' + req.user.name);
});
app.get('/user/:id/edit', function(req, res){
res.send('editing ' + req.user.name);
});
app.put('/user/:id', function(req, res){
res.send('updating ' + req.user.name);
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000);
Alternatively you can do nothing because all route which does not match will produce a 404. Then you can use this code to display the right template:
app.error(function(err, req, res, next){
if (err instanceof NotFound) {
res.render('404.jade');
} else {
next(err);
}
});
It's documented in Error Handling.
I bet your browser is following up with a request for the favicon. That is why you are seeing the 404 in your logs after the 200 success for the requested page.
Setup a favicon route.
You can this at the end of all routes,
const express = require('express');
const app = express();
const port = 8080;
// All your routes and middleware here.....
app.use((req, res, next) => {
res.status(404).json({
message: 'Ohh you are lost, read the API documentation to find your way back home :)'
})
})
// Init the server here,
app.listen( port, () => {
console.log('Sever is up')
})
Hope it helpful, I used this code in bottom of routes
router.use((req, res, next) => {
next({
status: 404,
message: 'Not Found',
});
});
router.use((err, req, res, next) => {
if (err.status === 404) {
return res.status(400).render('404');
}
if (err.status === 500) {
return res.status(500).render('500');
}
next();
});
You can use this
const express = require('express');
const app=express();
app.set('view engine', 'pug');
app.get('/', (req,res,next)=>{
res.render('home');
});
app.use( (req,res,next)=>{
res.render('404');
})
app.listen(3000);
I wanted a catch all that would render my 404 page only on missing routes and found it here in the error handling docs https://expressjs.com/en/guide/error-handling.html
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(404).render('404.ejs')
})
This worked for me.
Very simple you can add this middleware.
app.use(function (req, res, next) {
//Capture All 404 errors
res.status(404).render("404.ejs")
})
404 error in a service is typically used to denote that the requested resource is not available. In this article we will see how to handle 404 error in express.
We need to handle the Error and Not-Found collectively as
Write two separate middleware for each,
// Import necessary modules
const express = require('express');
// Create a new Express app
const app = express();
// Define routes and middleware functions
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Catch 404 Not Found errors and forward to error handler
app.use((req, res, next) => {
const error = new Error('Not Found');
error.status = 404;
next(error);
});
// Error handler middleware function
app.use((err, req, res, next) => {
// Set status code and error message based on error object
res.status(err.status || 500);
res.send({
error: {
message: err.message
}
});
});
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});

Resources