我是React-apollo的新手我只想弄清楚如何使用apollo进行服务器端渲染,它总是抛出一个错误404,我很确定我的 grapiql端点正在工作。
这是我的错误
{ Error: Network error: Network request failed with status 404 - "Not Found"
at new ApolloError (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\errors\ApolloError.js:32:28)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:268:41
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:705:25
at Array.forEach (native)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:702:27
at Array.forEach (native)
at QueryManager.broadcastQueries (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:699:42)
at Array.<anonymous> (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:65:23)
at dispatch (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\redux\lib\createStore.js:186:19)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\ApolloClient.js:174:30
graphQLErrors: [],
networkError:
{ Error: Network request failed with status 404 - "Not Found"
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\transport\networkInterface.js:116:33
at process._tickCallback (internal/process/next_tick.js:109:7)
response:
Body {
url: 'http://localhost:3000',
status: 404,
statusText: 'Not Found',
headers: [Object],
ok: false,
body: [Object],
bodyUsed: true,
size: 0,
timeout: 0,
_raw: [Object],
_abort: false,
_bytes: 140 },
parseError:
{ Error
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\node-fetch\lib\body.js:48:31
at process._tickCallback (internal/process/next_tick.js:109:7)
name: 'FetchError',
message: 'invalid json response body at http://localhost:3000 reason: Unexpected token < in JSON at position 0',
type: 'invalid-json' } },
message: 'Network error: Network request failed with status 404 - "Not Found"',
extraInfo: undefined,
queryErrors: [ [Circular] ] }
这是我的server.js
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import expressGraphQL from 'express-graphql';
import schema from './GraphQL/Schema';
import React from 'react';
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router';
import { ApolloClient, createNetworkInterface, ApolloProvider } from 'react-apollo';
import { getDataFromTree } from "react-apollo"
import store from '../client/Redux/Store/store';
require('es6-promise').polyfill();
require('isomorphic-fetch');
import WApp from '../client/App';
//Dev HMR
import HMR from './serverUtils/HMR';
const app = express();
app.use(bodyParser.json());
app.use('/api', expressGraphQL({
schema,
graphiql: true
}));
app.use('/static',express.static('build'));
HMR(app);
function Html({ content, state }) {
return (
<html>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: content }}/>
<script src="/static/app.js" />
<script dangerouslySetInnerHTML={{
__html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace(/</g, '\\u003c')};`,
}} />
</body>
</html>
);
}
app.get('*',(req,res) => {
const context = {};
const client = new ApolloClient({
ssrMode: true,
// Remember that this is the interface the SSR server will use to connect to the
// API server, so we need to ensure it isn't firewalled, etc
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000',
opts: {
credentials: 'same-origin',
// transfer request headers to networkInterface so that they're accessible to proxy server
// Addresses this issue: https://github.com/matthew-andrews/isomorphic-fetch/issues/83
headers: req.headers,
},
}),
});
const app = (
<StaticRouter location={req.url} context={context}>
<ApolloProvider store={store} client={client} >
<WApp/>
</ApolloProvider>
</StaticRouter>
);
getDataFromTree(app).then(() => {
const content = ReactDOMServer.renderToString(app);
const initialState = {[client.reduxRootKey]: client.getInitialState() };
const html = <Html content={content} state={initialState} />;
console.log('Initial State',initialState);
res.status(200);
res.send(`<!doctype html>\n${ReactDOMServer.renderToStaticMarkup(html)}`);
res.end();
}).catch(err => console.log(err))
});
app.listen(3000,() => {
console.log('Man I on')
})
根据答案更新
它给我一个像这样的错误{ Error: Network error: Network request failed with status 200 - "OK"
at new ApolloError (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\errors\ApolloError.js:32:28)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:268:41
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:705:25
at Array.forEach (native)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:702:27
at Array.forEach (native)
at QueryManager.broadcastQueries (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:699:42)
at Array.<anonymous> (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\core\QueryManager.js:65:23)
at dispatch (C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\redux\lib\createStore.js:186:19)
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\ApolloClient.js:174:30
graphQLErrors: [],
networkError:
{ Error: Network request failed with status 200 - "OK"
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\apollo-client\src\transport\networkInterface.js:116:33
at process._tickCallback (internal/process/next_tick.js:109:7)
response:
Body {
url: 'http://localhost:3000/api',
status: 200,
statusText: 'OK',
headers: [Object],
ok: true,
body: [Object],
bodyUsed: true,
size: 0,
timeout: 0,
_raw: [Object],
_abort: false,
_bytes: 37593 },
parseError:
{ Error
at C:\Users\arfo\Desktop\all folder\FinalHustleBoilerPlate\node_modules\node-fetch\lib\body.js:48:31
at process._tickCallback (internal/process/next_tick.js:109:7)
name: 'FetchError',
message: 'invalid json response body at http://localhost:3000/api reason: Unexpected token < in JSON at position 0',
type: 'invalid-json' } },
message: 'Network error: Network request failed with status 200 - "OK"',
extraInfo: undefined,
queryErrors: [ [Circular] ] }
提示:由于json解析错误我正在添加根查询文件我正在使用带有假数据的axios
import { GraphQLObjectType ,GraphQLNonNull,GraphQLID,GraphQLList} from 'graphql';
import axios from 'axios';
//All types
import PostType from './Post_Type';
const RootQueryType = new GraphQLObjectType({
name:'RootQueryType',
fields:{
posts:{
type:new GraphQLList(PostType),
resolve(parentValue,args){
return axios.get('https://jsonplaceholder.typicode.com/posts' )
.then(res => res.data)
}
},
post:{
type:PostType,
args:{ id: { type:new GraphQLNonNull(GraphQLID) } },
resolve(parentValue,{id}){
return axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(res => res.data)
}
}
}
});
export default RootQueryType
答案 0 :(得分:1)
尝试:
const client = new ApolloClient({
// ...
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000/api',
// ...
})
});