首页 > 解决方案 > 使用 Apollo 获取 XML restapi 返回意外的令牌

问题描述

我开始构建我的 ApolloClient。看起来像这样

import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client"
//import { RestLink } from "apollo-link-rest"
import fetch from "isomorphic-fetch"
const xml2js = require("xml2js")

const parseXmlResponseToJson = xml => {
// The function is not being fired
  const { parseString } = xml2js
  let jsonFeed = null
  parseString(xml, function (err, result) {
    jsonFeed = result
  })

  return jsonFeed
}

const restLink = new HttpLink({
  uri:
    "https://cors-anywhere.herokuapp.com/https://www.w3schools.com/xml/note.xml",
  responseTransformer: async response =>
    response.text().then(xml => parseXmlResponseToJson(xml)),
  fetch,
})

export const client = new ApolloClient({
  link: restLink,
  cache: new InMemoryCache(),
})

提供者看起来像这样

import React from "react"
import { client } from "../apollo"
import { ApolloProvider as Provider } from "@apollo/client"

function ApolloProvider({ children }) {
  return <Provider client={client}>{children}</Provider>
}

export default ApolloProvider

我尝试使用的查询看起来像这样

import React from "react"
import gql from "graphql-tag"
import { useQuery } from "@apollo/client"

const APOLLO_QUERY = gql`
  {
    note {
      to
      from
      heading
      body
    }
  }
`

const Component = () => {
  const { loading, error, data } = useQuery(APOLLO_QUERY)

  console.log("Apollo data", loading, error, data)

  The error will return with Unexpected token < in JSON at position 2 
  // ...

这几天我一直在为此苦苦挣扎。我究竟做错了什么?我尝试使其与 w3schools 一起工作,非常简单的 xml 示例https://www.w3schools.com/xml/note.xml

标签: reactjsgraphqlgatsbyapollo

解决方案


推荐阅读