Loading Images in Phaser and Node js - javascript

Im am trying to load images in phaser with node js and i always get the same error
:3000/assets/img/feet/idle/survivor-idle_0.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)
if you know a way to get this to work please tell me. here is my code:
preload() {
// Used for preloading assets into your scene
//Idle feet image
this.load.image('idleFeetFrame', '/assets/img/feet/idle/survivor-idle_0.png');
}
(Updated from Comment)
... is my server code:
const express = require('express');
const app = express();
const server = app.listen(process.env.PORT || 3000);
app.use(express.static('./public'));
console.clear();
console.log('\x1b[36m%s\x1b[0m', 'Server started...\n');
const socket = require('socket.io');
const io = socket(server);
io.sockets.on('connection', handleConnection);
function handleConnection(socket) { console.log('Client: ' + socket.id + ' has connected.') }

Since there are not any special routes configured in express, I assume all your files are in the folder ./public.
In that case the file survivor-idle_0.png would have to be in the folder ./public/assets/img/feet/idle/survivor-idle_0.png if you can't find it in that path, that is the problem (check for typos, or extra folder like src).
As long as you are not using a bundler like webpack, parcel or so, just need to check your the public folder and fix the paths.
If you are using a bundler, you will have to check the bundler configuration for errors.

Related

Express server don't search static files in Angular 12 app

Background
I am migrating an Angular app in GKE cluster. The base docker image that I must use(company policy) does not have any options to install any new softwares like shell, Angular cli command ng etc. The base docker image has only Node installed.
There is a shared base url, let's say, www.my-company.com, that everyone has to use for app deployment with a path added after the base url like www.my-company.com/my-angular-app/ - all the other Angular apps must be differentiated using the path of the app.
What I did
Since I can't run ng serve command in the base image, I added Express dependency in the package.json in Angular application and created an express server to route the traffic to Angular app.
I was following this youtube video to configure the application - https://www.youtube.com/watch?v=sTbQphoYbK0&t=303s. The problem I am facing is to how I load the the static files in the application.
If I define absolute path inside sendFile method of server.js file, although the application is working, but in future, if I need to add any other files in the application, I have to create another route in server.js file.
I don't know how Express can search a file automatically from the static folder(and sub folders) and return only that file when needed. I defined a static folder too, but seems like it is not working.
Following is my server.js code
==============================
const express = require('express');
const http = require('http');
const path = require('path');
const port = 8080;
const contextPath = '/my-angular-app';
const router = express.Router();
const app = express();
app.use(contextPath, router);
app.listen(port, ()=> {
console.log("Listening on port: ", port);
});
app.use(express.static(__dirname + '/dist/testapp/'));
router.get('/', function(req, res) {
// to get index.html file
res.sendFile(path.resolve(__dirname + '/dist/testapp/index.html'));
});
router.get('/*', function(req, res) {
let path = __dirname +'/dist/testapp/' + req.path
console.log('full path: ', path);
// To return static files based on incoming request, I am facing problem here(I think)
res.sendFile(path);
});
==============================
I want Express will send any files based on file name in the request. It should also take care of nested directories in the /dist/testapp/ directory
/dist/testapp/ -> This is the directory where Angular generates code for my app after I execute ng build command
WEBAPP.get("/admin/script.js", (req, res) => {
console.log(req.path);
if (req.session.username !== "Admin") return res.render("error");
res.sendFile(__dirname + "/admin/admin.js")
});
WEBAPP.get("/admin", (req, res) => {
if (!req.session.loggedin) return res.render("error");
if (req.session.username !== "Admin") return res.render("error",);
res.render("admin", {
csrfToken: req.csrfToken(),
title: "ADMIN PORTAL",
username: req.session.username,
nav_avatar: GetImageURL(req.session.avatar, "small")
});
});
There's no need to publically share /admin/script.js in my case but if a user requests this URL say example.com/admin/script.js a check for username equaling "Admin" if all is okay we sendFile.
I would maybe assume that you're not properly targeting your static files. Perhaps console.log the target.

How do i fix this error: localhost/:1 Failed to load resource: the server responded with a status of 404 (Not Found), Cannot Get /

I'm creating an online multiplayer .io game similar to https://diep.io/ or https://agar.io/ and I'm in the process of setting up a server this is my code,
var path = require('path');
var http = require('http');
var express = require('express');
var socketIO = require('socket.io');
var publicPath = path.join(__dirname, '../client');
var port = process.env.PORT || 2000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(port, function () {
console.log('Server stared on port ' + port);
});
When I start the server and put "localhost:2000" into the search bar this is what comes up,
I'm kinda new to this so if you could make the answers simple to understand then I'd really appreciate it.
Double check your paths. Your code will work as written if you have a folder structure like so:
/server/index.js
/client/index.html
$ node server/index.js
The static middleware by default will serve files which match html, html.
So if you have index.html, you can make a request to /, and if you have hello.html, you can hit it at /hello.
See here for more options: http://expressjs.com/en/resources/middleware/serve-static.html
Note: this middleware is what Express.static uses, so no need to install that package, just look at examples for serveStatic() and pass those to Express' version.

How do I make Node.js reference the CSS for my HTML

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.

Does log4js require any extra code to work on an Apache server?

I'm trying to add Log4js-Node to a Node.js server running on Apache. Here's my code:
const path = require("path");
const express = require("express");
const log4js = require('log4js');
const app = express();
const logger = log4js.getLogger();
logger.level = "debug";
const port = 443;
log4js.configure({
appenders: { everything: { type: 'file', filename: 'logs.log', flags: 'w' } },
categories: { default: { appenders: ['everything'], level: 'ALL' } }
});
const server = app.listen(port, () => {
logger.debug("listening to requests on port " + port);
});
app.get("/log", (req, res) => {
res.sendFile(path.join(__dirname + "/logs.log"));
});
When I run the script on Node.js on my computer and navigate to localhost:443/log I see what I expect, which is this:
[2020-03-17T22:50:43.145] [DEBUG] default - listening to requests on port 443
But when I run the code on a remote server it crashes and I get this in the error page (with part of the path replaced by me with "[removed]"):
App 25925 output: at Server. ([removed]/index.js:27:9)
App 25925 output: at Logger. [as debug] ([removed]/12/lib/node_modules/log4js/lib/logger.js:124:10)
App 25925 output: at Logger.log ([removed]/12/lib/node_modules/log4js/lib/logger.js:73:12)
App 25925 output: at Logger._log ([removed]/12/lib/node_modules/log4js/lib/logger.js:90:16)
App 25925 output: at Object.send ([removed]/12/lib/node_modules/log4js/lib/clustering.js:97:15)
App 25925 output: [removed]/12/lib/node_modules/log4js/lib/clustering.js:97
App 25925 output: at Object. ([removed]/12/lib/node_modules/log4js/lib/clustering.js:8:13)
I'm using A2 Hosting which uses Apache 2.4.41. I opted for Node.js 12.9.0, and Log4js 6.1.2. The package.json should be the same on both my computer and the server, and I've run npm install on both.
Is this just an issue with Log4js and the server, or have I missed something somewhere?
This was actually a relatively simple fix. The path referenced by the last error in the stack trace is a Log4js module that implements clustering support through Node's "cluster" module. The line "8" referenced is cluster = require("cluster"). It's wrapped in a try/catch block like this:
try {
cluster = require("cluster"); //eslint-disable-line
} catch (e) {
debug("cluster module not present");
disabled = true;
}
The installation of Node.js on my computer came with the "cluster" module, however as far as I can tell, the server I'm using doesn't support it. Also, the version of Node I'm using on my computer is newer than what I'm using on the server (so I've now installed 12.9 on my machine). I believe the older version of Node doesn't bother trying to catch the exception and tries to load the cluster module, fails, and then throws the error.
So the simple fix was to comment out most of the "try/catch" block, leaving just the contents of "catch" like this:
// try {
// cluster = require("cluster"); //eslint-disable-line
// } catch (e) {
debug("cluster module not present");
disabled = true;
// }
If someone has a better fix, I'm open to suggestions.
The same response of #skittleswrapper,thx, it work for me.
I use Node.js 14.18.1 with log4js 6.3.0.
But i wondering what'is the necessary of this module 'cluster' and if we can
add it to our app in other way.

express.js to GET json file in terminal

How do I GET a JSON file with express.js? I want to be able to access it in my Mac terminal. I'm working on a college assignment that asks me to write an HTTP server that will act as a simple data store. It must respond to GET, PUT, POST, and DELETE requests. I must use express.js instead of fs for this app.
So far, in my root directory I have a server.js file and I have a subdirectory called lib that holds another subdirectory called notes. Notes is where the JSON files will live.
In my root directory, I have a server.js file. This is all I have so far:
'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';
app.use(bodyParser.json());
app.get('/', function(req, res) {
//
//this is the part I need help with
//
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server started on port ' + port;
});
Once I have this GET request working, from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.
...from my Mac terminal I should be able to send a GET request and
receive all JSON files inside the notes directory.
Provided you do not want to use fs module(well you dont need one either),
you can simply set a route for GET requests and send the json file in response with app.sendFile()
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
//assuming your app.js and json file are at same level.
//You may change this to 'lib/notes/foo.json' to fit you case
})
path is a module that you would need to require().
__dirname is the directory that the currently executing script is in.
and finally foo.json is the file containing your json
{
"name":"nalin",
"origin":"stackoverflow"
}
Here's the complete code for app.js
var express = require('express');
var path = require('path');
var app = express();
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
})
app.listen(3000);
Which will help you run the node server with node app.js.
Finally you can access the json with by
visiting http://localhost:3000/ on your browser
by running curl command on your mac terminal curl localhost:3000
Hope this helps.
You can serve your .json files as static:
app.use('/notes', express.static( notes ));
http://expressjs.com/starter/static-files.html
Or you can do it manually width path pattern:
app.get('/notes/:file', function(req, res) {
fs.readFile(notes + "/" + req.params.file, function(err, data) {
if(err) {
res.status(404).send('Not found');
} else {
res.contentType(req.params.file);
res.send(data);
}
res.end();
});
});

Categories

Resources