reactjs - 使用 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
解决方案
推荐阅读
- javascript - 为什么在登录框外单击时模式登录不关闭?
- python - cross_val_score() 退出并出现 Killed 警告
- javascript - Rails 6 + webpack:TypeError:this.getOptions不是函数
- c++ - 如何使函数不知道其 const 参数的分配器?
- visual-studio-2019 - 在 Visual Studio 2019 16.9.4 中构建时未创建 .cgi 文件
- python - 用列表作为值反转字典(不能作为键重复)
- ios - 放大和缩小 SpriteKit 场景的数学
- c# - 如何在 c# windows 10 UWP 中圆化 App 主窗口的角?
- php - 为什么常规数据匹配条件在 ' 中不起作用
'?为什么它不给出输出? - java - 使用 MockMVC 对 RestController 端点进行单元测试,未按预期捕获预期的异常