My goal is
To print a message to my console when a user enters a specific page
To make it possible to access a page without having to write the .html extension.
If i use the following, where test.html is not an existing page, i will see
the expected message in my console when the user tries to access /test or /test.html page.
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log('User trying to access test.html page')
res.send('welcome to test page')
})
But if i do the same for an existing page (/dashboard.html)
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log('User trying to access dashboard.html page')
res.send('welcome to dashboard page')
})
I will see the expected message in my console when the user tries to access /dashboard but when he tries to access /dashboard.html the page will just load without seeing any message in my console.
Why is this happening?
I think the problem is that you are telling your app to use the static files before you tell your app to use your router.
I mean, if you do this (let´s say we have in the public folder the dashboard.html file):
const express = require("express");
const app = express();
const router = express.Router();
const port = 3000;
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log("User trying to access test.html page");
res.send("welcome to test page");
});
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log("User trying to access dashboard.html page");
res.send("welcome to dashboard page");
});
app.use("/", router);
app.use(express.static("public"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
It should work as you expected.
However it seems you are placing the app.use(express.static...) before the app.use router. Something like this:
const express = require("express");
const app = express();
const router = express.Router();
const port = 3000;
app.use(express.static("public"));
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log("User trying to access test.html page");
res.send("welcome to test page");
});
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log("User trying to access dashboard.html page");
res.send("welcome to dashboard page");
});
app.use("/", router);
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
So in this case when you type the exact path for the dashboard.html it won´t use the router to resolve the content and it will simply take it from the public folder.
It is just a matter of order for the app.uses(...) in the code
Related
I am new to express and using it for a game interaction. My problem is that when accessing root url I expected a simple hello world to come up, but I'm being served the html from a different endpoint.
On my server.js, I have:
const path = require('path');
const express = require('express')
const app = express()
app.use(express.json())
const { resetGame, takeTurn, checkWinner } = require('./logic.js');
const PORT = 8080
app.use(express.static('public'));
Then, I've set the following requests:
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/connect4', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/connect4', (req, res) => {
const bodyInfo = req.body
let clickedRow = bodyInfo.row
let clickedColumn = bodyInfo.column
currentState = takeTurn(clickedRow, clickedColumn)
currentState = checkWinner()
res.send(currentState)
});
app.post('/reset', (req, res) => {
currentState = resetGame()
res.send(currentState)
});
app.get('/fail', (req, res) => {
res.status(400)
res.json({ errorMessage: "missing parameters" })
})
app.listen(PORT, () => {
console.log(`Express server up on port: ${PORT}`)
})
When starting the server on my local and accessing localhost, I expected:
localhost:8080/ > to give me "Hello, World!"
localhost:8080/connect4 > to serve me html and run game functionalities
Although I have 2. working fine, 1. is also serving me the html and I can run the game functionalities there, as in / is giving me the same as /connect4.
Any ideas on why is this happening and what could I do to if I want that hello world in root?
I watched a Youtube video & copied the code from it but my page is not loading properly, It looks like this-
Node.js code -
import express from "express";
import bcrypt from "bcrypt";
//init server
const app = express();
//middlewares
app.use(express.static("public"));
app.use(express.json())//enables from sharing
//routes
//home route
app.get('/', (req, res) => {
res.sendFile("index.html", {root : "public"})
})
// 404 route
app.get('/404', (req, res) => {
res.sendFile("404.html", {root : "public"})
})
app.use((req, res) => {
res.redirect('/404')
})
app.listen(3000, () => {
console.log('listening on port 3000');
})
You are using a file: path inside of your HTML code (or other public files) which isn't possible as you aren't reading from a filesystem, you are using HTTP. Use proper paths instead in your links.
In the example below, if I'm in localhost:5000/A and i want to go to localhost:5000/B, but from within localhost:5000/A, how can i do that via a button ?
var express = require('express');
var app = express();
// Our first route
app.get('/', function (req, res) {
res.send('Hello Index!');
});
// Our A route
app.get('/A', function (req, res) {
res.send('Hello A!');
});
// Our B route
app.get('/B', function (req, res) {
res.send('Hello B!');
});
// Listen to port 5000
app.listen(5000, function () {
console.log('Dev app listening on port 5000!');
});
Just try this :
app.get('/A', function (req, res) {
res.send('Hello A! <button>Click me</button>');
});
Or you could serve an HTML page containing this code.
Hope this answers your question. If not please reach back to me.
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')
})
I am debugging into a NODE JS application and I am very new to node js. I have a REST module file
students.js
module.exports = function (service) {
/**
* Retrives data from DB
*/
service.get('/mobile/students', function (req, res) {
res.set('Content-Type', 'application/json')
.status(200)
.json(DBHelper.getAllStudents());
});
service.post('/mobile/students', function (req, res) {
res.status(200).json(data);
});
});
To run it locally I am using the following app.js
const express = require('express');
const app = express();
var routes = require('./students');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3010, function () {
console.log('Example app listening on port 3010!')
});
When I hit
http://localhost:3010/students, I am hitting a 404.
How do I explicit route the path to the student modules?
you need to add routes(app); line after var routes = require('./students'); then Your routes will be mounted..
http://localhost:3010/students if use this it will prompt you again with 404 but if you use http://localhost:3010/mobile/students it will produce desire output..