Express routing does not work with simple test case - javascript

I think I am missing some concept with basic routing for Express. See here
I created some simple test code as follows in my server index.js file.
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
In my browser(chrome) URL I type
localhost:3000/foo
to trigger the route but I get no response on the server or client.
I verified localhost:3000 is up and running.
Port is set in a different file as follows:
app.set('port', (process.env.PORT || 3000));
But also I get confirmation in the terminal as follows:
const server = app.listen(app.get('port'), () => {
console.log('DEBUG: express: server up');
});
I am on a campus network that blocks some traffic, but b.c. this is localhost I don't think it should matter.

I don't think you're supplying enough information to correctly debug your issue.
I'd initially ensure that Express is listening on port 3000, double-check this line:
app.listen(3000);
Ideally, this line should be at the bottom of the script.
Response to edit: Yes, this should not matter. localhost is an alias for the system itself. It's a loopback, similar to that of 127.0.0.1.

It seems like you have created two express app, as you have mentioned that you are using two different files, the localhost which you are able to run is the one which has app.listen() code, but this doesn't have the app.get()
I suggest you use a single file for now and try doing it.
Try out the following code, and check now with localhost:3000/foo.
const express = require('express')
const app = express()
const port = 3000
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

Related

When i use express and use ''use'' request to get response this came in my chorme bowser Cannot GET

iam new in node.js .iam faceing this problem .When i use express and use ''use'' request to get response to the chorome but this erro came in my chorme bowser Cannot GET.
or my app.js file or index.js is in one same folder . folder name is static. Iam not good in english please help me. Or if i use nodemon togther than when i get to localhost the the loaclhost cannot and show this 'This site can’t be reached'
i dont know how to fix it can any help me to fix this problem this the code
const express = require("express");
const app = express();
const port = 8080;
app.use('/static',express.static('express/static'));
app.get("/", (req, res)=>{
res.status(200).send("This is the first page of node express");
});
app.get("/about", (req, res)=>{
res.send("This is the about page of node express");
});
app.post("/postabout", (req, res)=>{
res.send("This is the postabout page of node express");
});
app.post("/erro", (req, res)=>{
res.status(404).send("This page has been errored in code of 404");
});
app.listen(80,'127.0.0.1', () =>{
console.log(`The application started and the port is ${port}`);
});
This the image of my code and chrome
In app.listen you passed wrong port means you intialized port as 8080 but passed 80
app.listen(8080,() =>{
console.log(`The application started and the port is ${port}`);
});
Basically, app.use function uses a middleware when a particular API is called it does not a get request.
So try app.get instead of app.use it will work.
app.get('/static', (req, res) => {
// Do your stuffs.
return res.send(response)
})

How to correctly call a function from Node.JS to Express.JS

I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)
const express = require('express')
const runParser = require("./parser");
const app = express()
const port = 3000
app.get('/', async (req, res,next) => {
await runParser()
next()
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
All you need for Express is this:
const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;
app.get("/", (req, res) => {
runParser().then(results => {
res.json(results);
}).catch(err => {
console.log(err);
res.status(500).send("error");
});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And, then you can access that either by just going to:
http://localhost:3000
from your local host or
http://yourdomain.com:3000
in the browser or by issuing an ajax call to the desired URL from webpage Javascript.
I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...
It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:
app.post("/runparser", (req, res) => {
// put your code here
});
And, then use a form submission or ajax call to that URL to trigger it.

How can i get response from another JavaScript file while working with nodejs and express?

I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).

What do I replace "http://localhost:3000" with when using a server and not local machine?

I've been doing a lot of online courses with node and express. I want to get sockets.io to work but I can't even establish a connection at the moment. I am using a cPanel virtual private server and running code in the server terminal and then trying to use a website hosted on the server to access the .js file running on the server.
I've tried all sorts of different things but I'm reducing it to its most basic level to try get a connection. All the videos I've seen are running on a local machine and using the command prompt on a local machine to run the .js file and the browser to access http://localhost:3000.
The .js file I'm running on my cPanel server looks like this;
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.send('Hello world 2');
})
app.listen(3000);
So how do I then access that via the browser? I have tried http://mywebsite.com:3000 and http://11.22.33.444:3000 if 11.22.33.444 is the server ip, but the browser just times out and there is no output in the server console.
ultimately I need to run a socket.io command that looks like this;
var socket = io.connect('http://localhost:3000');
and in all the tutorials I've seen they use this localhost:3000 but no one explains how to access this if its on an actual server so I'm pretty lost.
There are other examples like;
...
const http = require('http').createServer();
...
http.listen(3000 => () => {
console.log('listening on port 3000');
});
That's just a snippet of the code but I'm wondering how I then access that 3000 port from the browser without http://localhost:3000
IF you read the docs you will see that there is a guide how to connect it with express: https://socket.io/docs/
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
// WARNING: app.listen(3000) will NOT work here!
app.get('/', function (req, res) {
res.status(200).json({ message: "Connected" });
});
io.on('connection', function (socket) {
console.log("somebody connected");
});
Think I just solved it. I tried a different port and it worked :/
No need to specify any address in io.connect()
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(process.env.PORT || 3000, function() {
});
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect();

How can I handle routing with express when I use a static site?

When the user goes to mydomain.com/game, I want the user to see what is displayed in my public folder. This works completely fine when I do this:
app.use('/game', express.static('public'))
The problem is that I want to extract some information from the URL, but as I do not know how to continue the routing when using a static site, I can't extract any information. For example, if the user inputs mydomain.com/game/123, I want to retrieve 123, but still route the person to my public folder, like mydomain.com/game does.
Any ideas on how to handle this problems?
This has worked for me in a similar situation
app.use('/game/:id', (req, res) => {
// do something with id
res.redirect(302, '/game');
}
Try to use two middlewares: first is your static middleware, the secont is the fallback, with id (123)
app.use('/game', express.static('public'));
app.use('/game/:id', function(req, res) { // when static not found, it passed to this middleware, this process it
console.log('your id', req.params.id);
res.send('ok');
});
If you are using react static files and you want to serve all react routes using express then you have to do thing like below-
1.First of all you have to run command in your react folder
npm run build
this will create your build folder in react app having one index.html file which you have to serve through express.
Now come to your server.js file and write there
const express = require('express');
var path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req,res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server up and running on port ${port} !`));

Categories

Resources