首页 > 解决方案 > SyntaxError:JSON 中位置 0 的意外标记 S

问题描述

我有一个 netlify 函数,它返回正确的数据以及我调用我的 api 的成功消息。虽然当我试图在我的反应前端显示数据时,它给了我一个错误,承诺状态被拒绝。

Promise{pending}
[[promiseStatus]]: rejected
[[PromiseValue]]: SyntaxError: Unexpected token S in JSON at position 0

从 graphql readWeight.js读取数据的函数

import fetch from 'node-fetch'

exports.handler = async() => {
  console.log("inside");
  const response = await fetch(
    'https://graphql.fauna.com/graphql',
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${API_SECRET}`
      },
      body: JSON.stringify({
        query:`
        {allweight{data{weight}}}
        `
      })
    })
    .then(res => res.json())
    .catch(err => console.log(err))
    //console.log(response.data.allweight.data.map(w=>console.log(w.weight)))
    //console.log(response)
  return {
    statusCode: 200,
    body: JSON.stringify(response)
  }
}

api.js

const readAll = () => {
  return fetch('/.netlify/functions/readWeight').then((response) => {
    console.log(response)
    return response.json()
  })
}

api.js 响应

Response {type: "basic", url: "http://localhost:3000/.netlify/functions/readWeight", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:3000/.netlify/functions/readWeight"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
__proto__: Response

应用程序.js

import React, { Component } from 'react'
import api from './api'

export default class App extends Component {
  state = {
    weight: []
  }
  componentDidMount() {
    // Fetch all todos
    console.log(api.readAll())
    api.readAll().then((t) => {
      this.setState({
        weight: weight
      })
    })
  }
render(){
return(
<h1>Test
          {this.state.todos}</h1>
)
}


}

标签: javascriptreactjsfunctionlambdanetlify

解决方案


推荐阅读