Multiplayer game in Phaser - the "script" element could not be loaded - express

How do you configure the server for this template ? => https://github.com/nkholski/phaser3-es6-webpack
I'm trying to do it by following this tutorial => https://gamedevacademy.org/create-a-basic-multiplayer-game-in-phaser-3-with-socket-io-part-1/?a=13
I added two dependencies: nodemon and express.
I created the server.js file with the server configuration.
const express = require('express')
const app = express()
const server = require('http').Server(app)
const path = require('path')
app.get('/', function(req, res) {
res.sendFile(path.resolve('index.html'))
})
server.listen(8081, function() {
console.log(`Listening on ${server.address().port}`)
})
In the package.json file, I added a command to start the server:
nodemon src/server/server.js
The server starts correctly but the indicated html file can not read the scripts (" The load failed for the "script" element with the source vendor.js and app.js").
Project structure: https://i.imgur.com/r4QcXoJ.png

I solved this problem by indicate to the folder in which the scripts are located .
In my case it was a folder called 'dev'.
Adding this line solved the problem:
app.use('/dev', express.static('dev'))

Related

How to use node server with Vue Vite bundler

Does someone know how to use Nodejs server instead of Vite own frontend dev server on the port 3000. I tried all command combinations like those below but with no success
vite
vite preview
vite preview --port:5000
Thanks
UPDATE Feb 8-th 2022
I have found a way. We have to add flag --watch to the vite build command, like: vite build --watch That way Vite will bundle only changes to the front-end and store it in the /dist folder but it will watch outside server like Nodejs. That way we can develop both front and back end file simultaneously and see the result immediately. We have to launch server file separately and serve index.html from there. If we use Nodejs and Express on the server side we also have to point default directory to be /dist because Vite will put bundled files there, like app.use(express.static(__dirname + '/dist'));. node will automatically serve index.html and other bundled files from this folder.
Basically you will set the middlewareMode to ssr on the server options:
const fs = require('fs')
const path = require('path')
const express = require('express')
const { createServer: createViteServer } = require('vite')
async function createServer() {
const app = express()
// Create Vite server in middleware mode. This disables Vite's own HTML
// serving logic and let the parent server take control.
//
// If you want to use Vite's own HTML serving logic (using Vite as
// a development middleware), using 'html' instead.
const vite = await createViteServer({
server: { middlewareMode: 'ssr' }
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
app.use('*', async (req, res) => {
// serve index.html - we will tackle this next
})
app.listen(3000)
}
createServer()
This is explained in the doc: https://vitejs.dev/guide/ssr.html#setting-up-the-dev-server
Update for Vite 2.x
For Vite 2.x set server.middlewareMode to true and appType to custom:
// ...
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom'
})

How can I link my express server to generated 'dist' directory?

I am getting this error, "TypeError: path must be absolute or specify root to res.sendFile"
root
-dist
|--index.html
|--index_bundle.js
-src
|-server
|-server.js
//server.js
var path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
let dataStorage = {};
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(express.static('dist'))
app.listen(8081, function(){
console.log('Server running on port 8081!')
})
app.get('/', function (req, res) {
res.sendFile('../dist/index.html') //need help setting this up
})
app.post('/formHandler', function(req, res){
//post to dataStorage here
})
I am trying to run an express server while also using webpack-dev-server for hot reloading.
I am having trouble with setting up the path to generated 'dist' file.
I am able to just run the webpack-dev-server without express and the file is working then.
Thank you
You can have access to it by serving It's content as express static.
const path = require('path');
app.use(express.static(path.resolve(__dirname, '../../dist'));
You can also define the path at which statics assets can be accessible like this
app.use('/', express.static(path.resolve(__dirname, '../../dist'));
As in your dist folder there are already an index.html file it will be rendered by default when visiting the / path in your browser. No need to specify the index.html file in you request URL

Built Vue SPA not working when using "publicPath"

I set a public path in vue.config.js like
module.exports = {
publicPath: '/subpath'
};
it works fine when I start the devlopment server with npm run serve (vue-cli-service serve). The app becomes available at localhost:8080/subpath which is exactly what I want. It uses vue-router and at least in development it seems to work perfekt with the /subpath as publicPath.
Problem
I am using Express to serve the app files. Running npm run build the app will be built and stored to ./dist folder (default output folder).
// simplified server.js
app.use(express.static(path.join(__dirname, '/dist')));
app.get('/', (req, res, next) => {
res.sendfile('./dist/index.html');
});
After starting my express server and visiting my browser at localhost:<port>/subpath or localhost:<port> it can't find the necessary files.
// EXAMPLE FROM BROWSER CONSOLE
GET http://localhost:5050/subpath/js/app.6c6daa90.js net::ERR_ABORTED 404 (Not Found)
Which somehow looks obvious to me but I don't know how to set the express server correctly to respect the publicPath setting . Maybe there is a different approach ?
Attempt #1
I made a little change in my express server.js
// app.use(express.static(path.join(__dirname, '/dist')));
/* NEW */
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
This way it should serve the static files from the /dist folder when requested with /subpath/app.js
Result
From Browser console when requesting localhost:<port>/subpath or localhost:<port>
Refused to load the font 'data:application/font-woff2;base64,<omitted>' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://localhost:5050/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
I played around with express.static and this combination seems to work for me
const path = require('path');
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static(path.join(__dirname, '/dist')));
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
const listener = app.listen(5050, () => {
console.log(`Open http://localhost:${port} in your browser`);
});
Sidenote : Adding connect-history-api-fallback was not required to solve the initial problem but is required for vue-router to work properly when in history mode.

Problem deploying only Apollo Server to heroku

I am deploying an Apollo Server for my database to heroku and it is giving an application error. It is not simply show that there is a problem with the get route, it says that the application has an error and the error logs say that the app is crashing. It runs fine locally.
I have set up the procfile with: web: node app.js .
I have tried it with the procfile removed.
I have set playground and introspection to true. I saw that that could be the problem but it did not seem to help.
The port is set to process.env.PORT || 8080 .
Here is the minimal code:
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const db = require('./models');
const typeDefs = require('./data/schema');
const resolvers = require('./data/resolvers');
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
context: { db },
introspection: true,
playground: true,
});
server.applyMiddleware({ app });
const PORT = process.env.PORT || 8080;
app.get('/', (req, res) => {
res.send('hello');
});
app.listen(PORT, () => {
console.log(`Server is ready at ${PORT}`);
});
I am also using some other functions (trying to set up a cron process), but those are commented out.
I would expect to get the / get route to at least say hello, or for the /graphql route to display playground. I am getting neither of those options.
It turns out that I needed to add the following to package.json:
"scripts": {
"start": "app.js",
...
}
And I needed to install packages listed in the heroku logs --tail, but I have had those errors before. Writing the script start key into the package.json file is for when you are deploying your server independently of your react (or client) side.

Unable to find module 'server', added express to Ember-Cli app

I've added an expressJS app inside my ember app so I can provide a backend API for my ember app.
My process:
npm install express --save
I created a folder called "server" in the route of my ember application and inside that a file called "server.js".
Yesterday I had it working fine, I already had my ember app running via ember s and tested out the express app using nodemon server/server.js and checking the endpoints I created with Postman.
However this morning when I've tried to run ember s I'm given the following error:
C:\Sandbox\tsodash>ember s
version: 2.3.0-beta.2
Cannot find module 'C:\Sandbox\tsodash\server'
Error: Cannot find module 'C:\Sandbox\tsodash\server'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Project.require (C:\Sandbox\tsodash\node_modules\ember-cli\lib\models\project.js:281:12)
at Class.module.exports.Task.extend.processAppMiddlewares (C:\Sandbox\tsodash\node_modules\ember-cli\lib\tasks\server\express-server.js:115:33)
at Class.<anonymous> (C:\Sandbox\tsodash\node_modules\ember-cli\lib\tasks\server\express-server.js:220:21)
at lib$rsvp$$internal$$tryCatch (C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1048:17)
at C:\Sandbox\tsodash\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:331:11
Naturally I assumed I just needed to use modules.exports = function(){ //..expressjs code}
Full Code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var btoa = require('btoa');
var config = require('./config');
var _ = require('lodash');
module.exports = function(){
var endPoints = config.endPoints;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 4200;
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function (req, res) {
res.json({
message: 'TSO Git Dash'
});
});
// ..
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port: ' + port);
}
Still no avail.
Folder structure:
Any ideas? I'm assuming it's something simple that I've missed. But I'm stumped.
As #locks suggested in the comments, there is an express server used in mocks and fixtures. The fix was simple, I renamed the folder and the JS file to "api" and ran ember s and it worked perfectly. It seems to have been a naming conflict.