SyntaxError: Unexpected end of input

Hi All, I hosted my react app on Netlify. I am getting

SyntaxError: Unexpected end of input

Here’s the code with bold text showing the line that gives the error,


const authenticationMech = (values) => {
setFormValues(values)

var formBody = [];
for (var property in values) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(values[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
// console.log(formBody);

const requestOptions = {
  method: "POST",
  mode: "no-cors",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin": "*",
  },
  body: formBody,
};

fetch("https://celebrated-sawine-2b01a9.netlify.app/.netlify/functions/index/api/getFromId&Password", requestOptions)
.then((response) => response.json())
  .then((data) => {
    if (data) {
      // console.log(data[0].name);
      navigate("/orderEntry", { state: { owner: data[0].name ,id:data[0].id} });
    } else return alert("Invalid credentials!");
  })
  .catch((error) => console.log(error));

};

What is the mistake I am doing? Please help

@Geethu-95 This is the kind of error that’s much easier to debug when looking at the real thing, as you’ll usually get a line number or it’ll point you to the precise line.

From what you’ve pasted the bit that jumps out to me is:

} else return alert("Invalid credentials!");

try

} else { return alert("Invalid credentials!"); }

@nathanmartin Thanks for your reply. As per your suggestion, ive corrected the line. But still same error. The error shows up in line >

.catch((error) => console.log(error));

Sorry, I can’t spot what’s wrong from what you’ve provided.

If you link to the actual site I may be able to see it, but from what I can see here there’s no obvious missing brackets.

Just a heads up too, the Netlify forums aren’t a place to get general coding help with your site, the community here will help you configure your site to deploy properly on Netlify, but the kind of issue you’re experiencing here seems to just be a general coding issue, which is better directed elsewhere.

Thanks for your reply @nathanmartin. So what I did was host the front end at https://courageous-boba.netlify.app and backend which is a function, at https://courageous-boba.netlify.app/.netlify/functions/api. They are in the same domain so no CORS issues I’m assuming. I am getting an empty response when trying to login by fetching data from DB n comparing.

There shouldn’t be, and you could confirm this by looking at the console/network tab of your browser Developer Tools.

I don’t see anything at all when visiting your site, and that’s because it’s breaking.

You have this element:

<script crossorigin src="..."></script>

I’m confident you also have a redirect in place, (either in a _redirects file or your netlify.toml), which is redirecting everything that isn’t found back to the index (as you’ve got an SPA), so something like /* /index.html 200.

Subsequently the path ... on your site is returning the contents of your index.html which you can verify by going here:

https://courageous-boba.netlify.app/…

The fact it’s being loaded in a script element but isn’t JavaScript is then causing the error:

image

1 Like

Yes, there’s no CORS issue as confirmed by the console tab.

I removed the line <script crossorigin src="..."></script> because im not dealing with CORS here.

Yes I have _redirects file with /* /index.html 200 in place.

The fact it’s being loaded in a script element but isn’t JavaScript is then causing the error, how do I resolve this problem? Is it because of any other setting?

If you go to React App and try to enter an ID and password, it gives empty response, as observed in the console.

I am using db4free.net as the database source. Do I need to change any settings to allow it to accept requests from any IP or similar?

If you’ve removed that script element, it’ll have been resolved by virtue of not being there.

Basically any file that you try to load, but doesn’t exist, is going to end up returning the contents of your index.html file, it was happening because there is no ... file.

I have no idea, but you should be able to determine if it is/isn’t connecting to the database by debugging your function.

I changed my _redirects file to


/api/*  https://courageous-boba.netlify.app/.netlify/functions/api  200

/home /index.html 200

/orderEntry /index.html 200

/changePassword /index.html 200

and reorder few lines in my api.js inside functions folder.

var express = require('express')
var mysql = require('mysql');
var bodyParser = require('body-parser')
const cors = require('cors')
var Json2csvParser = require('json2csv').Parser;
const fs = require('fs')
const serverless = require('serverless-http')


const app = express()
const router = express.Router()


var con = mysql.createConnection({
  host: "db4free.net",
  user: "user",
  password: "password",
  database: "database"
});

con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
});

app.use(cors());

app.use(express.json())


app.use(bodyParser.urlencoded({
  extended: true
}));


router.get('/', (req, res) => {
  res.json({
    hello: "hi!"
  });
})



// Route for creating the post
router.post('/api/create',  (req, res) => {
  // const item = req.body;

  const orderDate = req.body.orderDate;
  const item = req.body.item;
  const count = req.body.count;
  const weight = req.body.weight;
  const requests = req.body.requests;
  const id = req.body.id;

  // console.log(item)
  // console.log(orderDate,company,owner,item,count,weight,requests)

  con.query("INSERT INTO Orderitem (order_date,item,count,weight,requests,user_id) VALUES (?,?,?,?,?,?)", [orderDate, item, count, weight, requests, id], (err, result) => {
    if (err) {
      console.log(err)
      // res.status(500).end()
    }
    res.send(result)
    // res.status(200).end()
  }
  );
})


router.post('/api/export-csv',  function (req, res) {

  const { id } = req.body;

  con.query("SELECT * FROM Orderitem WHERE user_id = ?", id, function (err, items, fields) {
    if (err) throw err;
    // console.log("users:");

    const jsonItems = JSON.parse(JSON.stringify(items));
    // console.log(jsonItems);

    // -> Convert JSON to CSV data
    const csvFields = ["order_id", "order_date", "item", "count", "weight", "requests", "user_id"];
    const json2csvParser = new Json2csvParser({ csvFields });
    const csv = json2csvParser.parse(jsonItems);

    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", "attachment; filename=orderItems.csv");

    fs.writeFileSync('orderItems.csv', csv)

    res.status(200).end(csv);

  });
});

app.listen(4000, () => {
  console.log(`Server is running on 4000`)
})

app.use('/.netlify/functions/api',router)

module.exports = app;
module.exports= router;
module.exports.handler = serverless(app)

Now I am able to fetch data, except for the /api/export-csv route which is giving a CORS error.

I’m seeing a blank page when I visit your site and don’t know how to trigger the API to see the CORS issue. If you can let me know, I can test and advise accordingly.

@hrishikesh Can you please go to > React App and check by entering id as 1234 and password as geethika1!. Then you will have to click on the export button on top

@Geethu-95 The site name isn’t the same when it’s making the request:

https://courageous-boba-89d4e4.netlify.app vs https://courageous-boba.netlify.app

While your login function hits:

https://courageous-boba.netlify.app/.netlify/functions/api/api/getFromIdAndPassword

2 Likes

@nathanmartin Aaah…My bad! Missed changing the URL when I changed the app name in Netlify.