Local Netlify function server gives strange response instead of FaunaDB data

236 views Asked by At

I am trying to build a simple web-app with Vue and a FaunaDB. When trying to fetch data from the DB i get the following error:

localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

When i print the response from the Netlify function server this is what i get:

enter image description here

Here is the code from the vue-page that tries to get the data:

  created() {
EventService.readAll()
  .then(response => {
    this.events = response.data
  })

}

This is the EventService Modul:

const readAllDates = () => {
  console.log("hey")
  return fetch('/.netlify/functions/read-all-dates').then((response) => {
    console.log(response)
    return response.json()
  })
}

export default {
  readAll: readAllDates
}

and this is my read-all-dates.js:

import faunadb from 'faunadb'

const q = faunadb.query
const client = new faunadb.Client({
  secret: process.env.FAUNADB_SECRET
})

exports.handler = (event, context, callback) => {
  console.log("Function `read-all-dates` invoked")
  return client.query(q.Paginate(q.Match(q.Ref("indexes/all_dates"))))
  .then((response) => {
    const dateRefs = response.data
    console.log("Todo refs", dateRefs)
    console.log(`${dateRefs.length} todos found`)

    const getAllDateDataQuery = dateRefs.map((ref) => {
      return q.Get(ref)
    })
    // then query the refs
    return client.query(getAllDateDataQuery).then((ret) => {
      return callback(null, {
        statusCode: 200,
        body: JSON.stringify(ret)
      })
    })
  }).catch((error) => {
    console.log("error", error)
    return callback(null, {
      statusCode: 400,
      body: JSON.stringify(error)
    })
  })
}

What am i doing wrong?

2

There are 2 answers

0
stanleyyyyyy On

Turns out it was vue-router which stopped the netlify proxy from directing the request to the right endoint. There seems no good way around this in dev: https://forum.vuejs.org/t/devserver-proxy-not-working-when-using-router-on-history-mode/54720

0
cjol On

The error you posted is one that it's worth getting familiar with!

localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Effectively this is caused when you try to parse something as JSON, but it's not actually JSON. The < is a tell-tale sign that the request response was probably HTML instead of JSON. The next step in debugging is to look at the XHR request itself in the browser debugging "Network" panel.

In my experience, one of the most common reasons for this error is a routing problem, which is triggering a 404 response route serving HTML instead of your expected function handler.