I'm trying to serve a very simple html page with one image. I'm using node.js and express. The html loads, but the image does not. Instead i am given the error GET https://localhost:3000/stockMarketPhoto.jpg 404 (Not Found) The image is in the same directory as everything else is. Somewhere I saw suggested that app.use(express.static('public')); is supposed to help with this, but no dice. I've tried both <img src="stockMarketPhoto.jpg"> and <img src="https://localhost:3000/stockMarketPhoto.jpg">. How can I get the image in my HTML page to load?
Here's the html in question
<body>
<img src="stockMarketPhoto.jpg">
</body>
Here's the javascript.
const https = require('https');
const express = require("express")
const fs = require('fs');
let app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log("listening on 3000");
});
app.get('/', (req, res) => {
console.log('connected');
res.sendFile(__dirname + '/index.html')
})
First i recommend you read this from the express docs.
Serving Static files in express
and in here:
<img src="stockMarketPhoto.jpg">
you are missing a '/' should look like this:
<img src="/stockMarketPhoto.jpg">
Your image should be inside the public folder in your app. What i do is usually put an Image, Javascript, and css folder inside my public folder and import them like this:
src='/Image/example.jpg'
src='/Javascript/example.js'
src='/css/master.css'
Basically when you tell express to serve your static files in the public folder, express then interprets the above example like this.
'public/Image/example.jpg'
Related
I want to develop a very basic blog app with express.js and I was trying to create a webpage where I could write a post from the browser and store it into a db after submitting it.
By searching on the internet I came upon the ckeditor package, which would allow me to format my blog post before submitting it to the database. I read the documentation and tried to integrate the package in the html code together with the javascript scripts necessary to load the software.
However, when I load the new_post page in my browser I see that the browser is not loading correctly the ckeditor even though I am serving the javascript script necessary to run it as a static resource through the express.static method.
Here you can find the necessary info to check my issue:
Project Structure:
project structure
app.js
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const PORT = 5000;
const newPostRouter = require(".\\routes\\new_post.js");
app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: false }));
//Homepage
app.get("/", (req, res) => {
res.render("homepage", { title: "My Express App", message: "Hello World!" });
});
//Write a new post
app.use("/new-post", newPostRouter);
//Listener
app.listen(5000, () => {
console.log(`Server listening on port ${PORT}...`);
});
routes/new_post.js
const express = require("express");
const router = express.Router();
const path = require("path");
router.get("/", (req, res) => {
res.render("new_post");
});
router.post("/", (req, res) => {
const title = req.body.title;
const content = req.body.content;
res.redirect("/");
});
module.exports = router;
views\new_post.ejs
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
</head>
<body>
<img src="..\public\dog-img.jpg" alt="derp" />
<h1>Classic editor</h1>
<div id="editor">
<p>This is some sample content.</p>
</div>
<script
src="..\public\js_scripts\new_post.js"
type="application\javascript"
></script>
</body>
</html>
public\js_scripts\new_post.js
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
As you can see I am trying to send the static resources to the client browser by using the express.static method in the app.js file. However when I try to load the page in the browser, this is the result I get:
result 1
The dog-img.jpg, also contained in the public folder, is correctly sent to the client yet the javascript file new_post.js is not.
I've also tried to modify the ejs file by substituting the script tag with
<script>
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
</script>
When I do this the editor correctly loads in my browser:
result 2
Since I am trying to follow the best practices I'd like to keep my js files separated from the html/ejs files and therefore I'd like to call the scripts from an external source and not internally.
Can anybody help me understand what is wrong with my code?
In app.js you need to write
app.use(express.static(path.join(__dirname, 'public')));
code to access all data inside the asset folder.
then you need to simple add or load this inside your .ejs file.
<img src="/images/img1.jpg" alt="" srcset="">
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/javascripts/index.js'></script>
For More Details Please visit this link Serving static files in Express
I am trying to serve images from an "images" file in my project depending on the parameters that the user enters.
For example,
https://localhost:3000/images?fileName=burger
should display the image on the browser
does anyone know how i can go about it?
My structure is as follows:
images
---burger.jpg
src
---index.ts
I tried to do it this way but for some reason it won't work
app.use('/images', express.static('images'));
if(req.query.fileName === "burger"){
res.sendFile("burger.jpg" , {root: path.join("./images")});
}
According to your code, if your file structure is following.your code will run perfectly. make sure you set the path to serving static files under express.static() with care and note that your incoming query value exactly matches the file you need to get including the case. this should solve the problem, thank you!
File Structure:
images
--- burger.jpg
index.js
import express from 'express';
import path from 'path'
const app = express();
const PORT = process.env.PORT || 5000;
app.use('/images', express.static('images'));
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile("rocket.jpg" , {root: path.join("./images")});
})
app.listen(PORT, () => {
console.log('Server is up and running on PORT: ${PORT}');
})
you can also avoid all those fuss by removing that middleware and instead provide absolute path while sending file. for eg:
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile(path.join(__dirname, "images/Rocket.jpg"));
}
})
I am trying to create a Turn Based strategy game like EU4 in JS. I would like to include multiplayer functionality but I want to understand why this keeps happening: When I run my app through node it seems to be that it only shows the bare HTML and not the CSS. Please help.
Code Below:
var express = require('express')
var app = express()
var serv = require('http').Server(app)
var port = 2000
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html')
})
app.use('/client', express.static(__dirname + '/client'))
serv.listen(port)
console.log('Colonial Warfare server => initialized!')
console.log('CWserver HostPort: ' + port)
var io = require('socket.io') (serv,{})
io.sockets.on('connection', function(socket) {
console.log('socket connection')
})
When your browser send the http request "/" you return your html that links to "/css/gameStyle.css".
You can either move your css folder to the client folder and change the link to "/client/css/gameStyle.css".
Or you can serve your css folder on the node app app.use(express.static('css'))
You need to serve the static CSS files by replacing the get for your index.html with the following line:
app.use(express.static('public'))
Change 'public' to 'client' if the CSS is next to your index.HTML.
Details here:
https://expressjs.com/en/starter/static-files.html
--EDIT--
As the index.html includes the css like "/css/filename.css" you have to host it like this:
app.use(express.static('css'))
or you change the references to your stylesheets to /client/css/filename.css in your html file.
Whenever you access an (for express) unknown path, express returns the index.html file.
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} !`));
I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.