Mac Hooper
Mac Hooper

Reputation: 115

Apollo Server network error: unable to reach server

I'm trying to develop a backend with Apollo Server, I have enabled cors in my browser and tried adding the cors: {origin: true} configuration in the server. I have included the server code below.

Hopefully someone is able to spot what I messed up on.

// index.js
const {ApolloServer} = require('apollo-server')
const typeDefs = require('./schema')
const resolvers = require('./resolvers')
const CourseAPI = require('./sources')

const apollo = new ApolloServer({
  typeDefs,
  resolvers,
  cors: {
    origin: true
  },
  dataSources: () => {
    return {
      courseAPI: new CourseAPI({
        client: 'pg',
        connection: {
          host: 'ec2-79-125-30-28.eu-west-1.compute.amazonaws.com',
          user: 'hgsfclebwdvtrz',
          password:
            '975260d79ace6b3f78132e6d51f8f56612e6cbc24c8d6063b9c6be60f5160453',
          database: 'd7jasm9tcmpc30'
        }
      })
    }
  }
})

apollo.listen().then(({url}) => {
  console.log(`🚀 Server ready at ${url}`)
})

Upvotes: 3

Views: 12227

Answers (5)

lovgrandma
lovgrandma

Reputation: 149

If you experience this in studio.apollographql.com/sandbox/explorer try running a query again to reauthenticate based on your server logic.

Upvotes: -1

therohantomar
therohantomar

Reputation: 469

I got the same error, in Next js With GraphQl But It Solved with

npm install micro-cors

import micro_cors from "micro-cors"

const cors = micro_cors({origin:"https://studio.apollographql.com",allowMethods:["GET","POST"],allowHeaders:["Access-Control-Allow-Credentials","true","Content-Type","Access-Control-Allow-Origin","Access-Control-Allow-Headers"]})

then Wrapping this

export default   cors(async function handler(req, res) {
          if(req.method==="OPTIONS"){
                    res.end()
                    return false
                   }

          
        await Server.createHandler({
                path:"/api/graphql"})(req,res);
                    })

And please Don't Forget To start the server

Upvotes: 1

therohantomar
therohantomar

Reputation: 469

else You Are Doing With Express-graphql/express this would be useful for You Schema.js

    //Importing all essential packages
      const {GraphQLSchema, GraphQLObjectType, GraphQLString, 
             GraphQLNonNull, GraphQLInt, GraphQLList} 
             =require("graphql")
      const slqite3=require("sqlite3")
      const db=new slqite3.Database("./database.json")


          // creating tables
                  const CreateTable=()=>{
          const Querii=`CREATE TABLE IF NOT EXISTS Books(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            AuthorId INTEGER
            
            )`

            const QueriiAuth=`CREATE TABLE IF NOT EXISTS Authors(
            
                AuthorId INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT
                
                )`

                db.exec(QueriiAuth)

            db.exec(Querii)

        }


      CreateTable()

          //Declaring BookType
        const BookType=new GraphQLObjectType({
        name:"Books",
        description:"All the books are here",
        fields:()=>({
        name:{
            type:GraphQLString,
        },
        id:{
            type:new GraphQLNonNull(GraphQLInt),
        },
        AuthorId:{
            type:GraphQLInt
        }
    })
})

//Declaring Author type
const AuthorType=new GraphQLObjectType({
    name:"AuthorType",
    description:"Authors list and details",
    fields:()=>({
        AuthorId:{
            type:GraphQLInt
        },
        name:{
            type:GraphQLString
        }

    })
})


// Declaring Root Query 

const rootType= new GraphQLObjectType({
    name:"Query",
    description:"All Queries Here",
    fields:()=>({
        Book:{
            type:BookType,
            args:{
                id:{
                    type:GraphQLInt
                }
            },
            resolve:(parent,args)=>{
                return new Promise((resolve,reject)=>{
            
                    db.all(`select * from Books where id=(?)`,args.id,(err,rows)=>{
                        if(err){
                            reject(err)
                        }
                        else{
                            resolve(rows[0])
                        }
                    })
                })

            }

        },
        Books:{
            type:new GraphQLList(BookType),
            resolve:()=>{
                return new Promise((resolve,reject)=>{
                    db.all("select * from Books",(err,rows)=>{
                        if(err){
                            reject(err)
                        }
                        else{
                            resolve(rows)
                        }
                    })
                    
                })
            }
     
        },
        Authors:{
            type:new GraphQLList(AuthorType),
            resolve:()=>{
                return new Promise((resolve,reject)=>{
                    db.all("select * from Authors",(err,rows)=>{
                        if(err){
                            reject(err)
                        }
                        else{
                            resolve(rows)
                        }
                    })
                    
                })

            }

        }

    })
})

//Mutation data 
const rootMutation=new GraphQLObjectType({
    name:"mutation",
    description:"Mutating data",
    fields:()=>({
        //add book mutation field
        addbook:{
            type:BookType,
            //arguments
            args:{
                name:{type:GraphQLString
                },
                AuthorId:{
                    type:GraphQLInt
                },

            },
            resolve:(parent,args)=>{
                console.log(args.name)
                return new Promise((resolve,reject)=>{
                    db.run(`INSERT into Books (name,AuthorId) values (?,?)`,args.name,args.AuthorId,(err)=>{
                        if(err){
                            reject(err)
                        }
                        db.all(`select last_insert_rowid() as id `,(err,row)=>{
                            if(err){
                                reject(err)
                            }
                            else{
                            
                                resolve({
                                    id:row[0].id,
                                    name:args.name,
                                    AuthorId:args.AuthorId
                                })
                            }
                        })

                    })

                })
            }
                
        
        },
        addAuthor:{
            type:AuthorType,
            args:{
                AuthorId:{
                    type:GraphQLInt
                },
                name:{
                    type:GraphQLString
                },

            },
            resolve:(parent,args)=>{
                return new Promise((resolve,reject)=>{
                    db.run("Insert Into Authors (name) values (?)",args.name,(err)=>{
                        if(err){
                            reject(err)
                        }
                        db.all("select last_insert_rowid() as id", 
       (err,row)=>{
                            if(err){
                                reject(err)
                            }
                            else{
                            
                                resolve({
                                    AuthorId:row[0].id,
                                    name:args.name

                                })
                            }
                        })
                    })
                })
            }
        }

    })
})



const Schema=new GraphQLSchema({
    query:rootType,
    mutation:rootMutation

})


module.exports=Schema

server.js file

const express=require("express")
const app=express()
const expressGraphQL=require("express-graphql").graphqlHTTP
const Schema=require("./Schema/schema")




//Middleware
app.use("/graphQl",expressGraphQL({
    graphiql:true,
    schema:Schema


}))



//PORT 
const PORT=process.env.PORT || 5000


// Listening On Port
app.listen(PORT,()=>console.log(PORT))

Upvotes: -1

Shazil Sattar
Shazil Sattar

Reputation: 61

I was facing the same error in crome and it turns out you have to configure apollo studio according to the subscription protocol you are using e.g. "graphql-transport-ws" or "subscriptions-transport-ws". You can fix this error by adjusting the configuration setting in the apollo studio. For more details

Upvotes: 0

Eyitayo Olaigbe
Eyitayo Olaigbe

Reputation: 81

I also have this particular error. It works perfectly in the playground but throw the error in studio explorer. I noticed something interesting though, accessing the explorer on google chrome works perfectly. I use Brave browser and was getting the error but it works fine on Chrome.

Maybe try using a different browser.

Upvotes: 5

Related Questions