Monday, 13 March 2017

"Uncaught SyntaxError: Unexpected token <" Error using Express and IIS

I'm currently using Express to render my web application. I used React and create-react-app to create my application. The issue comes from the main.8b78c8f8.js file when express tries to render index.html from the main build directory. Here is my express.js code. I would post main.js file, but it is a minified js file created by create-react-app.

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var cors = require('cors')
var http = require('http');

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '/build')));
app.use(cors());

app.get('*', (req,res) => {
    res.sendFile(path.join(__dirname+'/build/index.html'));
});

app.post('/api', (req,res) => {
    console.log("Initializing function");
    var surveyData = JSON.parse(JSON.stringify(req.body));
    console.log(surveyData);

    var arr = [];

    for (var x in surveyData){
        console.log(x + " = " + surveyData[x]);
    }

    res.send(req.body);
    fs.exists('./surveydata/surveydata.txt', function(exists){
        if(exists){
            fs.appendFile('./surveydata/surveydata.txt',           JSON.stringify(surveyData) + "\r\n", function (err) {
            if (err) return console.log(err);
        });
        } else {
            fs.appendFile('./surveydata/surveydata.txt', JSON.stringify(surveyData) + "\r\n", function (err) {
            if (err) return console.log(err);
            });
        }
    });

    console.log("Survey data > surveydata.txt");
    res.end("yes");
});


var server = app.listen(process.env.PORT, function() {
    console.log(__dirname+'build\index.html');
    console.log('Express server listening on port ' + server.address().port);
});

The < issue comes from the main.8b78c8f8 reaching some HTML, but interprets it as Javascript. This only happens when I try to reach my web application via URL (I have IIS and iisNode running on a Windows Server). If I run the web application from localhost, everything works fine.



via Andy Wong

No comments:

Post a Comment