Expressjs使用graphql-yoga

时间:2018-11-17 01:52:42

标签: node.js express graphql

我正在尝试使用api在后​​端构建一个简单的graphql-yoga。我有两个文件:index.js,其中路由文件被调用,并且graphql-yoga被初始化并且服务器正在运行;第二个文件routes.js,其中已定义要使用API​​的所有其他路由。 当使用有效的api键访问浏览器中的任何非graphql url时,例如:mylocalhost.tld/anything?api_key=randomValues,我能够访问资源而没有任何错误反馈。但是当访问诸如mylocalhost.tld/graphql?api_key=randomValues之类的graphql路由时,我得到了Not Found的反馈。 当我在routes(app);中注释掉index.js并访问mylocalhost.tld/graphql/(*)时,其中(*)可能是游乐场,我可以访问graphql资源。

所以我需要帮助的是能够访问mylocalhost.tld/graphql/(*)而不会收到404错误反馈。

index.js

     /**
     * index.js
     */

    // graphql
    import { GraphQLServer } from 'graphql-yoga';
    import graphql from '../graphql/schema';

    // other imports
    import routes from './routes';
    import os from 'os';


    // host
    const host = "http://" + (process.env.NODE_ENV === 'production' ? os.hostname() : "localhost");
    const port = process.env.PORT || 3060;


    // options
    const opts = {
        endpoint: '/graphql',
        port: port,
        tracing: true,
        playground: '/graphql/playground',
        cors: {
        origin: [host + ":3000"] // your frontend url.
      },
    }

    // context
    const context = (req) => ({
      req: req,
    });

    // server
    const server = new GraphQLServer({
        schema: graphql,
        // Align with behavior from express-graphql
        context: context,
    });

    // express
    const app = server.express;

    //Routes "./routes.js"
    routes(app);



    /**
     * Start server
     */
    server.start(opts, () => console.log(
        'Server listening at %s:%s in %s environment. \n',
        host,
        port,
        app.set('env'),
        ),
    );

    export default app;

    // ------------------------------------------------------------------ //

routes.js

    /**
     * routes.js
     */

    import authApi from '../lib/api';


    export default (app) => {



      app.use('*', authApi); // this lets all routes request for a valid api key before delivering resources

      /**
       * Extract GraphQL API Key
       */
      app.use('/graphql/:api_key?', (req, res, next) => {
        req.api_key = req.params.api_key;
        next();
      });

    }; // end of app

0 个答案:

没有答案
相关问题