nodejs, Express Cannot GET / - node.js

I try to run simplest Express code on Cloud server
var express = require('express');
var app = express();
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
I am getting the Apache 404 error : GET /cood180119/projExpress1/demo1/test HTTP/1.0, Cannot GET /cood180119/projExpress1/demo1/test
I have noticed that my url is http://77.xx.xx.xx/cood180119/projExpress1/demo1/test
while error logs shows IP : 88.xx.xx.xx.
How to resolve?
I have a node hello world example, which is working with the following url:
http://77.xx.xx.xx/node-hello-world-master/
where the file is in public_html/node-hello-world-master/app.js,
but does not work with http://77.xx.xx.xx:3000/
const http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end("Hello, World!\n port= ' + process.env.PORT);
}).listen(process.env.PORT); //is says that port is undefined
I set the port=3000 in environmental node variables.
After this, i can get the port number echoed , but i still can not access webpage using ttp://77.xx.xx.xx:3000/
Seems firewall is configured wrong.

I think you are requesting the wrong URL.
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
this will always produce a route as follows
'http://ip:3000/test
why do you use cood180119/projExpress1/demo1 in your URL. I don't see any route defined for that.

Your route
app.get('/test', (req, res) => res.send('Hello '));
make sure that the URI (or the path in this case /test) of the request you want to capture exists.

My problem:
The name of html file was not exactly "index.html"
So, I renamed it and it worked perfectly!
app.use(express.static('public'));
Note: public is a folder inside my server directory witch contains index.html and styles.css.

Related

NodeJS get params from URL -> httprequest and express both not working

I'm running a NodeJS application and am visiting it at localhost/?product=test. I want to retreive 'test' (or any URL-related information for that matter).
Google shows me 2 options, but I can't get either to work:
Use HttpRequest
const http = require('http');
const url = require('url');
http.createServer(function (req, res) {
const queryObject = url.parse(req.url,true).query;
console.log(queryObject);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Feel free to add query parameters to the end of the url');
}).listen(3000);
I'm trying to use this code, or variations on it, but the issue is that I cannot create a server to listen to because the address is already in use. I'm not too familiar with NodeJS, but what I don't understand is how to use a HttpRequest properly to listen to the running application and get its URL.
Use Express
Using express doesn't give an error, but all code snippets that -should- work return undefined for me when retrieving the URL.
What is a simple way to retrieve the URL the user used to visit my NodeJS app, so I can retrieve the parameters?
If you want to access localhost without filling in a port like here localhost/?product=test then you should listen to port 80 and not 3000. Otherwise your request should look like this: localhost:3000/?product=test
You should also create a route method for products. In express it will look like this:
const express = require('express')
const app = express()
const port = 80
app.get('/', (req, res) => res.send('home'))
app.get('/product/:productId', function (req, res) {
res.send(req.params)
})
app.listen(port, () => console.log(`Listening on port ${port}!`))
If you run this example your request url should be http://localhost/product/test and response will look like
{
"productId": "test"
}

Express enable client side caching

I am trying to cache a file client side with NodeJs and Express.
Here an example of what I am trying to do :
const path = require('path');
const express = require('express')
const app = express()
app.get('/', (req:any, res:any)=> res.send('Hello World!') );
app.get('/file', (req:any, res:any)=> {
console.log('Request URL:', req.originalUrl);
res.set('Cache-Control', 'public, max-age=60');
res.sendFile(path.resolve(__dirname+'/../file.pdf'));
});
app.listen(3000, ()=>console.log('Example app listening on port 3000!') );
Then I browse the file twice and I expect to have only one log Request URL: /file. But with this code I got two. It seems that either my Cache-Control headers is ignored by the browser or it get mixed up with default Express behavior like ETag..
Any Idea ?
I'm not sure but first thing that I thought about was the file size.
Maybe it is too big?
what-is-chrome-default-cache-size-limit

Webpack proxy messing up my routing?

So I'm using webpack for a project on 8080 with a backend on 3000. The proxy seems to work fine, as I can send requests to the backend and access it without issue. However. I need to include this middleware that allows me to have a user load the page, and if they've logged in within a certain amount of time, the initial request they send to the server logs them in automatically.
router.use(function (req, res, next) {
//check token for routes beneath vvvv
})
router.post('/preauth', function (req, res) {
//return user account info if req.token is valid
})
When I try to get to prauth, or even any route before that from the page loaded on 8080 I only touch the middleware and nothing else.
When I do npm run build then try it again from the identical page on 3000, it works as expected.
No, CORS is not enabled and the proxy does not rewrite any url.
Does anyone know if something in my Webpack config might be causing this?
You need install Cors in nodejs:npm install cors, you can try the following below or you see: Nodejs + Vuejs
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('This is a CORS-enabled web server listening on port 80')
})

Need to understand why expressjs is redirecting to index.html

I have the following server file, using express:
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
app.listen(port);
console.log('Listening on port: ' + port);
// get an instance of router
var router = express.Router();
app.use('/', router);
app.use(express.static(__dirname + "/"));
// route middle-ware that will happen on every request
router.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url + " logging all requests");
// continue doing what we were doing and go to the route
next();
});
// home page route for port 8080, gets executed when entering localhost:8080
// and redirects to index.html (correctly and as expected)
router.get('/', function(req, res) {
console.log("routing from route")
res.redirect('index.html');
});
// This gets executed when my url is: http://localhost:8080/test
// and redirects to index.html (the questions is why!? I thought
// all the requests to root route would be caught by the router instance
app.get('*', function(req, res){
console.log('redirecting to index.html');
res.redirect('/index.html');
});
Looking at the code above and my comments, I cannot understand why
app.get('*', function(){...})
does not get executed when URL is
localhost:8080/index.html but gets executed when URL is localhost:8080/test
Even though, this is the behavior that I was hoping for, I'm not sure why this works?
I don't have a "test.html" page in the root.
One other thing, the index.html does load other scripts, so I expected
app.get('*', function(){...})
to get executed for such get requests too, as it is supposed to be the catch all, but it does not.
Does app.use('/', router) mean that any route that has single character "/" should be handled by Router instance (as long as not a static file)? so "http:localhost:8080" gets interpreted as "http://localhost:8080/"?
I would appreciate any explanation.
This line-
app.use(express.static(__dirname + "/"));
will run first. It will see that index.html exists and serve that file statically.

POST Request fail with Node.js and Express.js

New web dev here, coming form the land of C, and everything is a little new :)
I'm working through some Express learning, and am stuck on getting POST requests to work. I'm using Advanced Rest Client on Chrome to send a POST request and am getting errors, no error number just a simple 'computer says no'.
My app.js:
var express = require('express')
, http = require('http');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.urlencoded());
app.use(express.json());
});
app.get("/", function(req, res) {
res.send("Hello, Express!");
});
app.get("/hi", function(req, res) {
var message = "Hello :-)";
res.send(message);
});
app.get("/users/:userId", function(req, res) {
res.send("<h1>Hello user #" + req.params.userId);
});
app.post("/users", function(req, res) {
res.send("Creating a new user with name " + req.body.username);
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
All the other routes work, just that POST that fails.
EDIT: Additional, I'm using text/html as the content type when I post.
I've restarted the server, ensured the file is saved, rebooted the system etc. I'm guessing the issue is the parsing of the body is failing. Any help would be great, cheers.
express.json() doesn't parse text/html, so you have no req.body inside your route handler, and req.body.username line will throw an error.
I've restarted the server, ensured the file is saved, rebooted the system etc. I'm guessing the issue is the parsing of the body is failing.
Don't guess. Debug and read logs (app.use(express.logger('dev')));

Resources