Apollo Server Express - Playground cannot be reached - node.js

I am trying to follow this tutorial https://www.youtube.com/watch?v=I6ypD7qv3Z8&t=48972s but I am stuck on trying to make the playground work.
I get to the playground on "http://localhost:4000/graphql" but somehow I get the "Server cannot be reached" error. In the network inspector I see "Cannot POST /" 404s.
Here's my code (app.ts):
import { ApolloServer } from "apollo-server-express";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
import { buildSchema } from "type-graphql";
import { PORT } from "./constants";
import { HelloResolver } from "./graphql/resolvers";
export const main = async () => {
const app = express();
const apolloServer = new ApolloServer({
schema: await buildSchema({ resolvers: [HelloResolver], validate: false }),
plugins: [ApolloServerPluginLandingPageGraphQLPlayground],
});
await apolloServer.start();
apolloServer.applyMiddleware({ app });
app.listen(PORT, () => {
console.log(
`Server started on http://localhost:${PORT}${apolloServer.graphqlPath}`
);
});
};
Things I did extra from the tut:
Made PORT a variable with value 4000
Added the "ApolloServerPluginLandingPageGraphQLPlayground" for the old school playground (newest doesn't work either)
Added the "await apolloServer.start();" line as specified on the doc, I get an error if I don't
Things I tried:
Using the http server stuff from the doc (https://www.apollographql.com/docs/apollo-server/integrations/middleware/#apollo-server-express) -> same issue
Any idea on where could be the issue? Seems like express didn't create the POST endpoint for the /graphql route.
EDIT: It works if I change this:
apolloServer.applyMiddleware({ app });
to this:
apolloServer.applyMiddleware({ app, path: "/" });

I found the answer here! helpful. Do check it out!

Try using 127.0.0.1 instead of localhost. It worked for me. Also If you have cached queries and mutations that you still want to use, switching back to localhost from 127.0.0.1 will have the localhost working again.

I recently had this issue too. This was the case where the
Server cannot be reached/no visible schema but still able to execute a query
To fix this you should have this as in your ApolloServer initializer:
const server = new ApolloServer({
csrfPrevention: true,
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground(),
],
instrospection: true,
})
Read more about instrospection here and this github issue.

Related

Is there a way to stop the playground from firing introspection query?

Iam using ApolloServer with ExpressJS. I disabled introspection in my apollo server , but Playground is still sending an introspection query.
setting the options:
introspection: false
and
settings: {
"schema.enablePolling": false, // or even "schema.polling.enable": false
}}
Doesn't change anything. I reloaded the playground but still doesn't change a thing. Here the ApolloServer config in my server.js file:
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
introspection: false,
playground: {
settings: {
"schema.enablePolling": false, // even "schema.polling.enable": false, does not work
}},
context: async ({ req }) => {
if(req){
console.log(req) // here we can see the introspection query firing every 2 seconds
}
}
});
What could be the reason(s) ?
Thanks

Jest+NextJs: You should only use "next/router" on the client side of your app

I'm mocking the next/router dependency in my Jest+React-testing-libray tests as I always have:
import * as nextRouter from 'next/router';
export const routerData = {
pathname: '/users/create',
route: '/users/create',
query: { },
asPath: '/users/create',
isFallback: false,
basePath: '',
isReady: true,
isPreview: false,
isLocaleDomain: false,
events: {},
};
// mock router
jest.mock('next/router');
nextRouter.useRouter.mockImplementation(() => (routerData));
describe('a component that requires next/router, () => ... );
This had been working correctly but after updating to NextJs 12.2.0 I get this warning:
No router instance found.
You should only use "next/router" on the client side of your app.
This warning makes all my tests with the mocked router to fail.
Ideas to fix this?
Well, it appears that this is not related to 12.2.0. Somehow my last version of Next - 12.0.0 - wasn't thrownig this error but other older versions did.
Thanks to bistacos for the response here.
const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
pathname: '/',
...moreRouterData
}));

How to fix this MongoClient connection?

I'm trying to connect a node.js app (written in TS) to MongoDB at Yandex Cloud. I have successfully connected there via mongosh:
mongosh "mongodb://<user>:<pass>#<host>:<port>/?replicaSet=<rs>&authSource=<db>&ssl=true" \
--tls --tlsCAFile ./YandexInternalRootCA.crt
where YandexInternalRootCA.crt is the downloaded certificate. Now I'm trying to do the same via MongoClient like this (the code is adapted from their examples; node v15.14.0, mongodb ^4.1.2):
import { MongoClient, Db } from 'mongodb'
import fs from 'fs'
const connnectionString = '<same connection string as the above argument of mongosh>'
const options = {
useNewUrlParser: true,
replSet: {
sslCA: fs.readFileSync('./YandexInternalRootCA.crt')
},
//tlsInsecure: true,
}
const getStorage = async (): Promise<Db> => {
// ts-ignore here is due to some typing problem: once you use 2 arguments
// in .connect, TS shows that it promises void (which is not true)
// #ts-ignore
return (await MongoClient.connect(connnectionString, options)).db()
}
Unexectedly, this results in
MongooseServerSelectionError: self signed certificate in certificate chain
I've tried to add tlsInsecure where it is show commented out (from suggestion for Mongoose), but it doesn't make a difference. What can be the cause and how can I fix this?
PS I've also tried various things like
const getStorage = async (): Promise<Db> => {
return (await MongoClient.connect(config.mongo.connectionUri, {
tls: true,
//sslCA: fs.readFileSync('./YandexInternalRootCA.crt'),
tlsCertificateFile: './YandexInternalRootCA.crt',
tlsInsecure: true,
})).db()
}
which still gives the same result.
If you use mongodb npm package version 4 or higher, you should pass TLS options like this:
const options = {
tls: true,
tlsCAFile: './YandexInternalRootCA.crt'
}

Unable to connect to AWS RDS using Sequelize ORM

I am working on an application which uses the Sequelize ORM to connect to AWS RDS. I have my connection set up as such:
Connection
import {Sequelize} from 'sequelize-typescript';
// Instantiate new Sequelize instance!
export const sequelize = new Sequelize({
"username": "AWS RDS USER",
"password": "AWS RDS PASS",
"database": "postgres",
"host": "******.******.us-east-1.rds.amazonaws.com",
dialect: 'postgres',
storage: ':memory:',
});
I also have defined a model to represent the database table which is defined as such:
Model
import {Table, Column, Model, CreatedAt, UpdatedAt} from 'sequelize-typescript';
#Table
export class FeedItem extends Model<FeedItem> {
#Column
public caption!: string;
#Column
public url!: string;
#Column
#CreatedAt
public createdAt: Date = new Date();
#Column
#UpdatedAt
public updatedAt: Date = new Date();
}
and exported as such:
import { FeedItem } from './feed/models/FeedItem';
export const V0MODELS = [ FeedItem ];
Then within my server.ts I import my sequelize connection and model and attempt to connect to my AWS RDS as such:
server.ts
import express from 'express';
import { sequelize } from './sequelize';
import { IndexRouter } from './controllers/v0/index.router';
import { V0MODELS } from './controllers/v0/model.index';
(async () => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
await sequelize.addModels(V0MODELS);
await sequelize.sync({ force: true, logging: console.log });
} catch (error) {
console.error(error);
}
const app = express();
const port = process.env.PORT || 8080; // default port to listen
app.use(express.json());
//CORS Should be restricted
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
app.use('/api/v0/', IndexRouter)
// Root URI call
app.get( "/", async ( req, res ) => {
res.send( "/api/v0/" );
} );
// Start the Server
app.listen( port, () => {
console.log( `server running http://localhost:${ port }` );
console.log( `press CTRL+C to stop server` );
} );
})();
When I run the program no connection is established, and the server fails to start. When I remove the sequelize.sync method, the server will start but my tables are not created. No error is caught by the catch block so I do not suspect there is an error. Currently I do believe this is connection issue dealing with postgres and AWS, but I cannot seem to pinned it down. All feedback and direction are appreciated.
I have found the issue. The problem was due to the node version I was using, which at the time was 14.15.3. This version is not compatible with my current version of postgres 13.1 so I used nvm and downgraded to node 11.15.0 and now my sequelize commands are working.
My node version is 16 and I am guessing Postgres 13 is not compatible with it hence, I had to downgrade my node version to 11.15.0.
Downgrade your node version to 11.15.0 by downloading nvm from here
Unzip the downloaded zip file and install. Click next and accept all default settings -- Do not customize the settings. If you have node already installed it might detect your current node version and ask to take control of it click yes.
After the installation process is done, open CMD or Powershell and type
nvm list
This is will show you the list of node versions installed, then type
nvm install 11.15.0
After installing the node 11.15.0 type
nvm list
To list the newly installed node version along with your previously installed node and then type
nvm use 11.15.0
Then go back to your vscode and run your project again.
#EDIT
If you're from ALX-Cloud Developer Program I suggest you downgrade your node version to 12 because Angular CLI version is only compatible with node v12 and above(at the time of writing this). Good luck!!!

Cannot set uncompiled validation rules without configuring a validator

I have downloaded a learning project so it is not my code, but when I want to start it getting this error. I tried to debug a little bit by myself but as I'm new to Nodejs so having a problem here...
Error: Cannot set uncompiled validation rules without configuring a validator
at Object.module.exports.register (/home/antonp/Desktop/pizza-luvrs/routes/index.js:25:10)
at startServer (/home/antonp/Desktop/pizza-luvrs/index.js:12:10)
here is the link for the full project. Github repo
index.js
const Hapi = require('#hapi/hapi')
const plugins = require('./plugins')
const routes = require('./routes')
async function startServer () {
const server = Hapi.Server({
port: process.env.PORT || 3000
})
await plugins.register(server)
routes.register(server)
try {
await server.start()
console.log(`Server running at: ${server.info.uri}`)
} catch (err) {
console.error(`Server could not start. Error: ${err}`)
}
}
process.on('unhandledRejection', err => {
console.log(err)
process.exit()
})
startServer()
Your issue is due to a change in hapi. Try changing the following code in pizza-luvrs-master/routes/login.post.js
validate: {
payload: {
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().min(3).max(30).required()
}
}
to
validate: {
query:Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().min(3).max(30).required()
})
}

Resources