Unable to send response using app.use in node js - node.js

code is used to set up server and calling a html page
const express =require('express')
const path=require('path')
const app=express()
const ppath=path.join(__dirname,'../public/index.htm')
app.use(express.static(ppath))
app.listen(3000,()=>
{**strong text**
console.log("HEy")
})

Try this.
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '..', 'public', 'index.htm'));
});

You pass express.static() a directory and it looks for requested files in that directory. You don't pass express.static() a path to a single file. That will not work.
If you actually want other static files in the same directory to be served, you could point express.static() at the parent directory.
Of, if you just want that one file served, then you just set up a route for that one file:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname,'../public/index.htm'));
});
For an further help with express.static(), we also need to know exactly what the incoming URL is that you want to serve index.htm with.

Related

React App giving 404 on main js and css

I built a react app using "react-scripts". The application runs perfectly on my local development server but when I deploy to my actual server the applications seems to not find the main JS and CSS files being compiled. I get 404 on both.
Following is the information that might help.
The files on the server are located at
ads/build/static/js and ads/build/static/css || respectively
The 404s I am getting are on the following files:
https://www.example.com/ads/build/static/css/main.41938fe2.css
https://www.example.com/ads/build/static/js/main.74995495.js
Here is how my server is configured:
const express = require('express');
const path = require('path');
const app = express();
const favicon = require('serve-favicon');
//favicon
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.get('/ads', function (req, res) {
app.use(express.static(path.join(__dirname, 'build/static')));
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.listen(9000);
In my package.json I have also included the homepage parameter as:
"homepage" : "https://www.example.com/ads
UPDATE
When I run the app on the server itself with the following path:
dedicated-server-host:9000/static/js/main.74995495.js that renders the JS file correctly
Is there some configuration that I am missing, the routing doesn't seem to be working. Please advise.
Use some indentation so you will see error like this:
app.get('/ads', function (req, res) {
app.use(express.static(path.join(__dirname, 'build/static')));
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
You are setting the static route inside of the /ads handler, will add a new express.static route handler on every GET /ads request.
This will set the static route on server startup:
app.use(express.static(path.join(__dirname, 'build/static')));
app.get('/ads', function (req, res) {
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
or:
app.get('/ads', function (req, res) {
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.use(express.static(path.join(__dirname, 'build/static')));
But make sure that you get the path right - for example you may need:
app.use('/ads/build/static', express.static(path.join(__dirname, 'build/static')));
if you want the URL in your question to work.
To make it much simpler, you could use just this single handler to make express.static handle both the css/js and index.html at the same time:
app.use('/ads', express.static(path.join(__dirname, 'build')));
and change your index.html to use:
https://www.example.com/ads/static/css/main.41938fe2.css
https://www.example.com/ads/static/js/main.74995495.js
instead of:
https://www.example.com/ads/build/static/css/main.41938fe2.css
https://www.example.com/ads/build/static/js/main.74995495.js
Sometimes getting your paths structure right in the first place can make your route handlers much easier.

Node.js + Express: What do I have to serve the specific folder's path to express.static?

I wrote the following code:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname ));
app.get('/', function (req, res) {
res.sendFile('./dist/index.html');
});
app.listen(3000, function() {
console.log("Listening on port 3000");
});
which doesn't work. When open the browser and go to "localhost:3000" I get the error:
path must be absolute or specify root to res.sendFile
Of course the once I fix the line that starts with "app.use..." to:
app.use('/', express.static(__dirname + "./dist"));
then everything works right.
Can you please explain why? What's wrong with giving "express.static" a path of a parent folder of the direct folder of the file sent?
Try changing the order. Instead of:
app.use('/', express.static(__dirname ));
app.get('/', function (req, res) {
res.sendFile('./dist/index.html');
});
Try:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, './dist/index.html'));
});
app.use('/', express.static(__dirname));
// OR:
app.use('/', express.static(path.join(__dirname, 'dist')));
Plus use path.join() to join paths. You need to require path first:
var path = require('path');
See this answer for more info on serving static files and why path.join is important:
How to serve an image using nodejs
Now, your problem was not about express.static but about res.sendFile. When you changed express.static path to a different one, then the file you previously wanted to send with res.sendFile was probably found by express.static and the handler with res.sendFile was not run at all. Before the change, the express.static wasn't finding the index.html file and was passing the request to the next handler - which had a bad res.sendFile invocation. That's why it appeared to solve the problem with the error, because the code causing the error was no longer called.

Intercept request for a static file in express.js

I have a node server, that serves static files in a PUBLIC folder like this:
var app = express();
app.listen(port);
app.use(compression());
app.use(express.static(__dirname + '/PUBLIC'));
There is a json file, let's say important.json that is located in /PUBLIC folder. This is being served as a static file
Now, I want to intercept request for this /PUBLIC/important.json, so that I can programatically return a random json structure instead.
None of the followings works:
app.get('/PUBLIC/important.json', function(req, res) {
console.log("caught1!")
});
app.get(__dirname + '/PUBLIC/important.json', function(req, res) {
console.log("caught2!")
});
app.get('important.json', function(req, res) {
console.log("caught3!")
});
How can I intercept request for that partically static file?
As the express.static middleware does not call the next middleware using next(), the definition order is important. You have to define your own middleware before using express.static.
app.get('/PUBLIC/important.json', (req, res, next) => {
console.log('caught');
next();
});
app.use(express.static(__dirname + '/PUBLIC'));
Could you tell us a bit more about your stack ?
Are you using nginx / apache to proxy_pass the traffic to your nodejs server ?
Are you just running your app with "node app.js"
Let's try to add this simple route in your application :
app.get('/', function (req, res) {
res.send('Hello World!');
});
And try to access it by removing URI parameters ? Does the "Hello world" show up ?
I just want to be sure the traffic is actually treated by your node app.
Your route definition is supposed to work for your actual request.

Node.js: how to make default page to be sth. other than index.html

Originally, my node.js server goes to index.html by default.
Now I want to default to login.html so people can log in first.
My code is in .../server/server.js, while client page are in .../client/login.html, index.html, etc.
Now I modified server.js to be like this:
app.get('/', function(req, res)
{
res.sendfile(path.resolve('../client/login.html'));
});
After restart server.js, the webpage is still pointing to index.html by default. What am I missing?
If you're running ExpressJS on top of Nodejs, you can serve the files statically using the static method. The first parameter is the directory and the second allows you to specify the default file.
app.use(express.static('../client/', {index: 'login.html'}))
http://expressjs.com/guide/using-middleware.html#middleware.built-in
For your specific example, you can modify the sendFile to include the root with the second parameter:
res.status(200).sendFile('login.html', { root: path.join(__dirname, '../client/') });
If you also have a router that's handling getting an index page for you and you want to render a handlebar page or do something else instead, you can put anything in the index option and it will ignore it if not found in your static asset folder:
app.use(
express.static(
path.resolve(__dirname, "../Client/assets/"),
{index: "userouterinstead"}
)
)
app.use("/", route_configs)
app.get("*", (req, res, next) => {
res.sendFile(
path.resolve( __dirname, "../Client/assets/index.html" )
)
})

Express and URL rewriting | HTML5 history

I'm trying to build a simple server to serve a single HTML page where all the logics are
handled by Angular. As far as I'm using the HTML5 history mode I'm able to navigate
through standard URLs.
Now, to make this work I need to enable URL rewriting. I tried with this bunch of lines and
although return always the correct HTML page, the URL vary and does not keep the initial
value. For example /popular should load index.html and leave the URL /popular so that the
JS logic can load the desired page.
Here follows the express code.
var express = require("express");
var app = express();
app.configure(function(){
app.use(express.static(__dirname + '/dist'));
});
app.get("/*", function(req, res, next){
res.sendfile(__dirname + '/dist/index.html');
});
app.listen(3000);
Any suggestion is appreciated.
Thanks everyone.
You need to set the root directory for relative filenames.
app.all('/*', function(req, res) {
res.sendfile('index.html', { root: __dirname+'/dist' });
});

Resources