Nodejs GraphQL не может подключиться к интерфейсу на локальном хосте

#node.js #graphql

#node.js #graphql

Вопрос:

Я настраиваю GraphQL API для доступа к базе данных PostgreSQL на локальном хосте, но в настоящее время я не могу подключиться к интерфейсу браузера GraphQL. Я проверил, что узел обновлен, и установлены зависимости graphql, конфигурации клиента верны, поскольку я могу получить доступ к базе данных через psql.

После того, как я запускаю node server.js в корневом каталоге и получаю доступ к api через его URL в браузере, он загружается вечно, и ничего не происходит. Код работает на компьютере моего партнера, поэтому я не уверен, что происходит.

Как я могу регистрировать любые ошибки после app.listen?

 const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const graphql = require('graphql')
const { Client } = require('pg')
const joinMonster = require('join-monster')

const client = new Client({
    host: "localhost",
    user: "postgres",
    password: "postgres",
    database: "postgres"
})
client.connect() 

......


const app = express()
app.use('/api', graphqlHTTP({
    schema: schema,
    graphiql: true,
}))

app.listen(4000, () => {
 console.log('Server running on port %d', 4000);
});
  

Комментарии:

1. Ваш код подходит для подключения к graphql, но я думаю, что проблема связана с pgSQL, поэтому использует seqlize ORM для pgSQL. npmjs.com/package/sequelize

Ответ №1:

 //server.js

import path from 'path';
import express from 'express';
import graphQLHTTP from 'express-graphql';
import cors from 'cors';
import config from './server/config/environment';
import schema from './server/data/schema';

if (config.env === 'production') {
  // Launch GraphQL
  const graphql = express();

  graphql.use(cors({credentials: true, origin: true}));


  graphql.use('/graphql', graphQLHTTP((req, res) => ({
      schema,
      graphiql: true
  }))
  );

  graphql.listen(config.port, () => {
    console.log(chalk.green(`GraphQL is listening on port ${config.port}`))
  });
}

//db.js



 import Sequelize from 'sequelize';
    import {Op} from 'sequelize';
    
    
    const sequelize = new Sequelize('', '', '', {
      host: 'localhost',
      port:5432,
      dialect: 'postgres',
      operatorsAliases: Op,
    })
    
    // model list
    const models = {
        Admin: sequelize.import('./admin'),
      };
    
    models.sequelize = sequelize;
    module.exports = {
        models
    }

// schema.js

var {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLID,
    GraphQLString,
    GraphQLInt,
    GraphQLBoolean,
    GraphQLList,
    GraphQLNonNull
} = require('graphql');

var Db = require('./db');

var Sectors = new GraphQLObjectType({
  name: 'sectors',
  description: 'list of all the sectors',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve (sectors) {
          return sectors.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve (sectors) {
          return sectors.name;
        }
      }
    };
  }
});

var Query = new GraphQLObjectType({
  name: 'Query',
  description: 'Root query object',
  fields: () => {
    return {
      sectors: {
        type: new GraphQLList(Sectors),
        args: {
          id: {
            type: GraphQLInt
          },
          name: {
            type: GraphQLString
          }
        },
        resolve (root, args) {
          return Db.models.sectors.findAll({ where: args });
        }
      }
    };
  }
});

var Schema = new GraphQLSchema({query: Query});
exports.default = Schema;