【问题标题】:Local Netlify function server gives strange response instead of FaunaDB data本地 Netlify 功能服务器给出奇怪的响应而不是 FaunaDB 数据
【发布时间】:2021-01-21 14:00:32
【问题描述】:

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

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

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

这里是 vue-page 中尝试获取数据的代码:

  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
}

这是我的全部日期.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)
    })
  })
}

我做错了什么?

【问题讨论】:

    标签: vue.js netlify faunadb


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您发布的错误值得熟悉!

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 2021-08-16
        • 2022-10-25
        • 2023-03-12
        相关资源
        最近更新 更多