Expressjs question

Is it possible to use php with express on glitch, and if so how?

This is my current config:

let express = require("express");
let app = express();
var phpExpress = require('php-express')
let listener = app.listen(process.env.PORT, () => {
  console.log(`Your app is listening on port ${listener.address().port}`);
});
let url = require("url");

let cors = require("cors");
let path = require("path");

app.use(cors());
// app.engine('php', phpExpress.engine);
app.set('view engine', 'php');
// app.all(/.+\.php$/, phpExpress.router);
let server = listener;
var host = server.address().address;
  var port = server.address().port;
  console.log('PHPExpress app listening at http://%s:%s', host, port);

app.get("/", (request, response) => {
  response.sendFile("/app/page/comingSoon.php")
})

app.get("/favicon.ico", (request, response) => {
  response.sendFile("/app/favicon.ico")
})

global.express = express;
global.app = app;
require('/app/loadS.js')

	const { execSync } = require('child_process');
	execSync('sh /app/begin.sh', { encoding: 'utf-8' });
let app = global.app;
let path = require('path');
let express = global.express;
app.use(express.static(path.join(__dirname, "assets")));

Hey @Callum-OKane I’ve never played with php-express so I can’t say off the top of my head. What specific issues or errors are you encountering?

Well, it just downloads the php file, but before I started using express, it worked just fine!

The project is “clever-deal” if you would like to take a closer look! Site here

This code should go in the listen() callback, otherwise it won’t get anything useful yet …

let server = listener;
var host = server.address().address;
  var port = server.address().port;
  console.log('PHPExpress app listening at http://%s:%s', host, port);

This is why you are getting sent the php file …

app.get("/", (request, response) => {
  response.sendFile("/app/page/comingSoon.php")
})

Instead try something like:

app.get("/", phpExpress.router);

Would probably need to have index.php …

That has not helped at all.

I have updated my code a bit, so this is what I am using now:
router/startSite.js

let express = require("express"),
  app = express(),
  phpExpress = require("php-express")({
    binPath: "php"
  }),
  listener = app.listen(process.env.PORT, () => {
    console.log(`Your app is listening on port ${listener.address().port}`);
  }),
  url = require("url"),
  cors = require("cors"),
  path = require("path"),
  server = listener,
  host = server.address().address,
  port = server.address().port,
  { execSync } = require("child_process");

app.use(cors());
app.engine("php", phpExpress.engine);
app.set("view engine", "php");
console.log("PHPExpress app listening at http://%s:%s", host, port);
global.express = express;
global.app = app;

    require('/app/router/page.js')
    require('/app/router/errors.js')
    require('/app/loadS.js')


router/page.js

let app = global.app,
  url = require("url");
app.get("/", (request, response) => {
  var parts = url.parse(request.url, true),
    query = parts.query,
    auth = query.auth,
    att = JSON.stringify(auth);
  console.log(auth)
  console.log(1)
  if(att === "88kjsog909gsjo0"){
    console.log(2)
    response.send("test")
  } else{
    console.log(3)
  response.sendFile("/app/page/comingSoon.php");
  }
});

app.get("/favicon.ico", (request, response) => {
  response.sendFile("/app/favicon.ico");
});

loadS.js

let app = global.app,
    path = require('path'),
    express = global.express;

app.use(express.static(path.join(__dirname, "assets")));
app.set("views", __dirname + "/page");

Turns out whatever I have after the url:
https://maniabots.xyz/somethinghere.extentsion

It downloads the file as I have it in the url, so if I did https://maniabots.xyz/oof.html
It will download it as a html file, named oof.

How about pass the filename to the render function, so the php engine can send it to the commandline?

app.get("/", (request, response) => {
  response.render("/app/page/comingSoon.php", {
    method: request.method,
    get: request.query,
    post: request.body
  });
});

(This time I tried the idea first :slight_smile: )

Ah, that has worked! But… it is not rendering any of the css or js…

Uncaught SyntaxError: Unexpected token <

  • Gives that error for the js file, even though, the file just contains “console.log(“hi”)”

clever-deal.glitch.me/:10 Resource interpreted as Stylesheet but transferred with MIME type application/x-httpd-php: “https://clever-deal.glitch.me/comingSoon.css”.

EDIT:
When I view the pages sources in inspect element, it has the php files content, inside the js file, same with the css.

Maybe comment out the interesting bits until you get down to a working minimal example?

Here’s what I got working, almost straight from the package example.

code example
const express = require('express');
const app = express();

// must specify options hash even if no options provided!
var phpExpress = require('php-express')({
  // assumes php is in your PATH
  binPath: 'php'
});

app.get("/", (request, response) => {
  response.render("/app/views/funky.php", {
    method: request.method,
    get: request.query,
    post: request.body
  });
});


// set view engine to php-express
app.set('views', './views');
app.engine('php', phpExpress.engine);
app.set('view engine', 'php');

// routing all .php file to php-express
app.all(/.+\.php$/, phpExpress.router);

app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
// app.get('/', function(request, response) {
//   response.sendFile(__dirname + '/views/index.html');
// });

// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' + listener.address().port);
});

You have a .js file with php inside it?

No I do not, I have a js file with a simple “console.log(“test”)”
But when I load the site, and go to sources on inspect element, it shows me that the js file, has the html/php of the page that I have loaded.

https://gyazo.com/184409d2474a9303cc9806fd899a0be0

Looks like your code above is missing this line or equivalent …

app.set('views', './views');

From how I understand it, the php engine will render as php the files in the path defined as views.

So you’d want to ensure the js file is in /public and not /views

Then mangle to your own structure as appropriate :slight_smile:

I already have that though… and the js and css files are not in the same folder.

I have this:

app.use(express.static(path.join(__dirname, "assets")));
app.set("views", __dirname + "/page");

and in the php file I have this:

    <link rel="stylesheet" href="comingSoon.css">
    <script src="comingSoon.js"></script>
    <link
      rel="stylesheet"
      href="css/fonts.css"
    />

https://gyazo.com/cdec9ee6585293047c156b63116d6208

@cori, Would you happen to have any ideas of what is going wrong and what I could do?


Nothing yet?

Resource interpreted as Stylesheet but transferred with MIME type text/html: “https://clever-deal.glitch.me/comingSoon.css”.

Why is this happening?

Have a look at the response header in the browser dev console, networking tab.

Express routing should automatically put the correct header according to filename extension.

I have noticed that it only occurs when I use this code:

app.use(function(req, res) {
  res.sendFile("/app/errors/404.html", 404);
});

app.use(function(error, req, res, next) {
  res.sendFile("/app/errors/500.html", 500);
});

I guess I’m no longer sure what problem you’re seeing here, @Callum-OKane - I seem to have lost the thread. In the current configuration I don’t see any mime-type issues, for example, at https://clever-deal.glitch.me/oof.html - I see what seems to be your styled 404 page.

Can you recap the current state of affairs?

Right, so the issue now is that when I include the express code for 404 and 500 error pages, it changes my css / js into the 404 page code when the site is loaded, which can be seen from dev tools sources section, but when I remove the 404 / 500 error page code for express, the js and css files load fine with the site.

I can reproduce the problem of the custom 404 page being delivered in place of other files, if I put the above routes before other routes, and after the / route.

The custom 404 route should be defined after all the other routes have been defined, because it is a “nearly catch-all” route that can match any url, so it should only be processed after the other routes have had a go at it.


res.sendFile("/app/errors/404.html", 404);

FYI to send this with the desired http status …

res.status(404).sendFile("/app/errors/404.html");

Well done isolating the problem, that’s a big diagnostic success! :slight_smile:

2 Likes

This is the current code I have now.

let app = global.app,
    url = require('url');


app.get("/", (request, response) => {
response.sendFile("/app/page/comingSoon.html");})
  
    app.get("/staffAuth", (request, response) =>{
    var parts = url.parse(request.url, true);
    var query = parts.query;
      let qer  = JSON.stringify(query)
    let res=response;
    if(qer === "{}") {
      console.log("fail2")
      response.sendFile("/app/page/admin/login.html")
      console.log(query)
      console.log("ThisIsATest")
      return;
    }
    if(query.username === "CallumTest") {
      console.log("pass1")
      if(query.password === "Password123") {
        console.log("pass2")
        res.send(`AUTH SUCCESS`)
      } else {
        console.log("fail1")
        res.sendFile("/app/page/admin/login.html")
      }
    }
    
});




app.get("/favicon.ico", (req, res) => {
  res.sendFile("/app/favicon.ico")
})


app.use(function(req, res) {
 if(res.status(500)) return res.sendFile("/app/errors/500.html");
if(res.status(404)) return res.sendFile("/app/errors/404.html");
})

It no longer shows the 404 code inside the files in sources, but now it shows the css file being completely blank.