2017-06-06 105 views
0

我需要向graphql端点发出自己的请求。 (默认实现使POST调用我们指定的url)。我需要做一个AJAX调用。我读它从: http://dev.apollodata.com/core/network.html#custom-network-interface与在ApolloClient中创建NetworkInterface相关的问题

它明确指出,我需要创建一个NetworkInterface并将其传递给ApolloClient。

我做了这样的事情:

const customInterface = { 
    query(request) { 
     return $.post(url_of_graphql_endpoint) 
      .send({query : request.query.loc.source.body}) 
      .end() 
      .then(result => result.text)  
    } 
} 

const client = new ApolloClient({networkInterface: customInterface}); 

ReactDOM.render((
    <ApolloProvider client={client}> 
    <Router history={browserHistory}> 
     <Route path='/' component={App} /> 
    </Router> 
    </ApolloProvider> 
), 
    document.getElementById('root') 
) 

网络请求被到graphql端点制成,并且服务器还具有易响应响应(即它应该发送)。

即使在此之后,我在浏览器中发生了一些错误,因此我无法显示从我的服务器获取的数据。组件始终处于“加载”状态。

Error in observer.error 
Error 
    at new ApolloError (<URL>:12345/bundle.js:22220:23) 
    at <URL>:12345/bundle.js:21680:39 
    at <URL>:12345/bundle.js:22168:25 
    at Array.forEach (native) 
    at <URL>:12345/bundle.js:22165:27 
    at <URL>:12345/bundle.js:81569:11 
    at baseForOwn (<URL>:12345/bundle.js:47066:20) 
    at forOwn (<URL>:12345/bundle.js:82561:20) 
    at QueryManager.broadcastQueries (<URL>:12345/bundle.js:22163:9) 
    at Array.<anonymous> (<URL>:12345/bundle.js:21595:23) 
    at dispatch (<URL>:12345/bundle.js:56461:19) 
    at <URL>:12345/bundle.js:64699:30 
    at Object.dispatch (<URL>:12345/bundle.js:17264:16) 
    at <URL>:12345/bundle.js:22130:33 
    at tryCatcher (<URL>:12345/bundle.js:7247:23) 
    at Promise._settlePromiseFromHandler (<URL>:12345/bundle.js:5269:31) 
    at Promise._settlePromise (<URL>:12345/bundle.js:5326:18) 
    at Promise._settlePromise0 (<URL>:12345/bundle.js:5371:10) 
    at Promise._settlePromises (<URL>:12345/bundle.js:5446:18) 
    at <URL>:12345/bundle.js:2169:25 
    at MutationObserver.<anonymous> (<URL>:12345/bundle.js:6501:17) 

回答

0

我是能够做到覆盖查询方法的功能,因此我只张贴了别人谁可能面临着同样的问题的答案。

我试图重写查询方法的方式是错误的。我是这样做的。

class CustomNetworkInterface extends HttpNetworkInterface{ 
    query(request){ 
       return $.post(url_of_graphql_endpoint) 
      .send({query : request.query.loc.source.body}) 
      .end() 
      .then(result => result.text)  
    } 
} 

为了制作ApolloClient,只需传递CustomNetworkInterface的对象。

const client = new ApolloClient({networkInterface: new CustomNetworkInterface(http://url)}); 

ReactDOM.render((
    <ApolloProvider client={client}> 
    <Router history={browserHistory}> 
     <Route path='/' component={App} /> 
    </Router> 
    </ApolloProvider> 
), 
    document.getElementById('root') 
)