0

我正在尝试使用 Vue 和 FaunaDB 构建一个简单的网络应用程序。尝试从数据库中获取数据时,出现以下错误:

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

当我打印来自 Netlify 功能服务器的响应时,我得到的是:

在此处输入图像描述

这是尝试获取数据的 vue 页面中的代码:

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

}

这是 EventService 模块:

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

export default {
  readAll: readAllDates
}

这是我的 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)
    })
  })
}

我究竟做错了什么?

4

2 回答 2

0

您发布的错误是值得熟悉的错误!

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

实际上,这是在您尝试将某些内容解析为 JSON 时引起的,但它实际上不是 JSON。这<表明请求响应可能是 HTML 而不是 JSON。调试的下一步是在浏览器调试“网络”面板中查看 XHR 请求本身。

根据我的经验,此错误的最常见原因之一是路由问题,它触发了服务 HTML 的 404 响应路由,而不是您预期的函数处理程序。

于 2020-10-07T11:18:47.507 回答
0

原来是 vue-router 阻止了 netlify 代理将请求定向到正确的 endoint。在开发中似乎没有什么好的方法: https ://forum.vuejs.org/t/devserver-proxy-not-working-when-using-router-on-history-mode/54720

于 2020-10-06T21:37:08.157 回答