gpt4 book ai didi

javascript - React-Apollo 抛出网络错误 404?

转载 作者:行者123 更新时间:2023-12-03 04:04:53 24 4
gpt4 key购买 nike

我是 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

最佳答案

尝试:

const client = new ApolloClient({
// ...
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000/api',
// ...
})
});

关于javascript - React-Apollo 抛出网络错误 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com