Saturday 6 May 2017

Can't Process PHP files with Node.js

I have a Node.js web app that I'm running on a Heroku server. I have an AJAX request in my javascript that sends a GET request to a PHP file on the server. That request is working fine, in fact, it works perfectly if I run it without any Node.js, and just a PHP web app, so I'm wondering what changes when I start with an index.js file, and node, instead of an index.php file and apache. For the sake of trying to figure this out, I have set the entire root directory as a public folder.

My index.js file is as follows:

var path = require('path');
var express = require('express');
var app = express();
var router = express.Router();
var phpExpress = require('php-express')({
    binPath: 'php'
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.set('port', (process.env.PORT || 5000));

app.use('/', express.static(__dirname));

app.set('views', path.join(__dirname, '/views'));
app.engine('php', phpExpress.engine);
app.set('view engine', 'php');

app.all(/.+\.php$/, phpExpress.router);

// Homepage
router.get('/', function(req, res, next){
    res.render('index.php');
});
app.use('/', router);

app.use(function (req, res, next) {
    res.status(404).send("Sorry can't find that!")
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});

In my browser javascript I have a simple GET request like this:

let xhttp = new XMLHttpRequest();
xhttp.open('GET', 'folder/file.php?name=' + $name, true);
xhttp.send();

Which works perfectly if I don't use Node.js, but returns the contents of the file.php, using Node.js. Chrome tries to download the file.

What's going on that causes this? Any help or advice would be much appreciated, thanks :)



via Jeremy E.

No comments:

Post a Comment