I am running into the follow error: Error: Query.totalPosts defined in resolvers, but not in schema - javascript

I am running into the error: Error: Query.totalPosts defined in resolvers, but not in schema. I have been looking for a solution but am unable to find a work around or a solution.
my server.js:
const express = require('express')
const {ApolloServer} = require('apollo-server-express');
const http = require('http');
const path = require('path');
const {fileLoader, mergeTypes} = require('merge-graphql-schemas');
// //resolvers`enter code here
const resolvers = {
Query: {
totalPosts: () => 42,
me: () => 'Gaia'
const typeDefs = mergeTypes(fileLoader(path.join(__dirname, './typeDefs')));
async function startApolloServer(typeDefs, resolvers){
const apolloServer = new ApolloServer({typeDefs, resolvers});
const app = express();
// typeDefs
// const typeDefs = mergeTypes(fileLoader(path.join(__dirname, './typeDefs')));
await apolloServer.start();
//this method connects Apollo server to a specific HTTP framework ie: express
apolloServer.applyMiddleware({app, path: '/graphql'});
apolloServer.applyMiddleware({ app });
const httpserver = http.createServer(app);
// rest endpoint
app.get('/rest', function(req, res) {
data: 'hit rest endpoint'
app.listen(process.env.PORT, function() {
console.log(`Server running at http://localhost:${process.env.PORT}`);
console.log(`Graphql server running at http://localhost:${process.env.PORT}${apolloServer.graphqlPath}`);
startApolloServer(typeDefs, resolvers);

Your field totalPosts exist in typeDef ?
As documentation said in step 3, https://www.apollographql.com/docs/apollo-server/getting-started/ , you have to define your graphql schema for use it.
Every GraphQL server (including Apollo Server) uses a schema to define the structure of data that clients can query. In this example, we'll create a server for querying a collection of books by title and author.
You should type something like this :
type Query {
totalPost: Int
me: String
And, when i build a graphql api on nest.js, schema file automaticly build. I guess, it's same way with express.
Did you try to setup your api following this doc : https://www.apollographql.com/docs/apollo-server/v2/integrations/middleware
typeDef look like automaticly resolve and push to a schema file. You may re-load your serve when it's should be update.
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');
async function startApolloServer() {
const app = express();
const server = new ApolloServer({
await server.start();
server.applyMiddleware({ app });
app.use((req, res) => {
await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
return { server, app };


Unable to setup Express server on HTTPS

Trying to set up my Express server on HTTPS but unable to access my api. Here is my code:
// server.js
const express = require('express');
const { readFileSync } = require('fs');
const https = require('https');
const app = express();
const key = readFileSync(
const cert = readFileSync(
const ca = readFileSync(
const credentials = { key, cert, ca };
const port = 443
const server = https.createServer(credentials, app);
server.listen(port, () => console.log(`Server is running on port ${port}`));
The error I am receiving is a 502 Bad gateway on all calls to the server.
Everything worked perfectly before when I was running on HTTP like this:
const server = app.listen(8000, () => {});
Beside the URL on my site I can see the padlock icon and it says my site is secure so I believe my certifcate is valid.
Have seen a lot of similar questions posted on here and followed what I've seen in responses. I've even asked chatGPT to check my code and it doesn't see any errors. I've also tried reading my SSL keys as .env variables so I don't think the issue is an incorrect file path.
Can anybody please help me find the solution?
Here is an example of a get request I am making to my backend using axios:
const fetchMembers = async () => {
await axios
This invokes a function totalUsers with express.Router from a users file in my routes folder on the backend:
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/total-users', totalUsers);
const totalUsers = async (req, res) => {
try {
const total = await User.find().estimatedDocumentCount();
} catch (err) {
I am using a middleware app.use with a prefix /api and importing the users file to make a connection to my endpoints:
// server.js
const userRoutes = require('./routes/users')
app.use('/api', userRoutes)
While editing this question I tried modifying the middleware prefix to `:443/api' however this still hasn't helped.
Where is User defined inside of routes/users.js? You need to import your DB models before accessing them like this:
const total = await User.find().estimatedDocumentCount();
Otherwise, generally when running fetch('/api...), React will try to access localhost:3000/api instead of localhost:443/api.
React needs to know where to proxy requests to the backend. One way is using the http-proxy-middleware library and by defining a setupProxy.js file.
* Proxy most calls to the server
* #type {Array}
/* eslint-disable #typescript-eslint/no-var-requires */
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxy_urls = ['/api/*';
const target = 'https://localhost:443';
module.exports = function (app) {
proxy_urls.forEach((url) => {
app.use(url, createProxyMiddleware({ target }));

How to open graphql playground page using apollo server express in 2022?

We have a API project using express with Apollo server express and graphql, I am new to graphql so I don't know how to land graphql playground page by default.
when I am trying to run it lands on "http://localhost:8080/graphql but it shows
The full landing page can not be loaded; it appears that you might be offline
can any one help me how to land graphql playground page?
I have followed the below code
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = gql`
type Query {
hello: String
const resolvers = {
Query: {
hello: () => 'Hello world!',
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
const port = 8080;
app.listen({ port }, () =>
console.log(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`),
Install apollo-server-core and add {ApolloServerPluginLandingPageGraphQLPlayground} it from the plugin section

Express routes stopped working after setting app in production on Heroku

I've deployed my app on Heroku and after some tweaking, everything works except when I try to retrieve data from the Mongo database. The console error I get is: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.
I have the feeling that it won't go into the get request while that should be the case. (Because it's not logging anything in the console)
Am I missing something in the way routes are handled in production?
Everything in development is working.
I'm very confused at this point, hope someone can help me
const bodyParser = require('body-parser')
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const MongoClient = require('mongodb').MongoClient;
const cors = require('cors')
const compression = require('compression');
const helmet = require('helmet')
const app = express();
const port = process.env.PORT || 5000;
if (process.env.NODE_ENV === 'production') {
const publicPath = path.join(__dirname, 'client/build');
const apiPath = path.join(__dirname, 'api');
app.use('/overview', express.static(apiPath));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
const apiRouter = require('./api/api');
app.use('/overview', apiRouter);
// connect to the db and start the express server
let db;
const url = process.env.MONGODB_URI
MongoClient.connect(url, {useUnifiedTopology: true,useNewUrlParser: true,}, (err, client) => {
if(err) {
return console.log(err);
console.log('mongo connected')
db = client.db('kvdlaanmeldingen');
// start the express web server listening on port 5000
app.listen(port, () => console.log(`Listening on port ${port}`));
apiRouter, api.js in api/api.js:
const express = require('express');
const apiRouter = express.Router()
const MongoClient = require('mongodb').MongoClient;
const mongodb = require('mongodb');
const url = process.env.MONGODB_URI
console.log('api.js is activated') //this is logged to console, so file can be read.
let db;
MongoClient.connect(url, {useUnifiedTopology: true,useNewUrlParser: true,}, (err, client) => {
db = client.db('kvdlaanmeldingen');
let aanmeldingen = [];
// this is where I believe it gets stuck
apiRouter.get('/', (req, res) => {
db.collection('kvdlaanmeldingen').countDocuments({}, function(err, result) {
if (err) return console.log(err);
module.exports = apiRouter;
The get request should be done as soon as this React component is rendered:
import React from 'react';
import './Aanmeldingen.css';
import { Link, Route } from "react-router-dom";
import XPress from './utils/Xpress.js';
import TaakComponent from './TaakComponent';
import { snakeCase } from "snake-case";
class Aanmeldingen extends React.Component {
constructor (props) {
this.state = {
dataLoaded: 0,
taken: [// an array of different names that will be loaded as headers],
taakKlik: false,
taakData: null,
taakNaam: null,
XPress.getTaken().then(data => {
if (data) {
taakData: data,
dataLoaded: 1,
return (
<div className="Aanmeldingenpage">
<div className="statistics" onClick={this.aanmeldingen}>
<p className="statistics" id="counterAanmeldingen">{this.state.dataLoaded ? `Aantal aanmeldingen: ${this.state.taakData}` : 'Data aan het laden..'}</p>
and Xpress.getTaken is looking like this:
const XPress = {};
const baseUrl = window.location.origin;
XPress.getTaken = () => {
const url = `${baseUrl}/overview`;
return fetch(url, {method: 'GET'}).then(response => {
if (!response.ok) {
return new Promise(resolve => resolve([]));
return response.json().then(jsonResponse => {
return jsonResponse
The error you posted is often seen when parsing JSON fails. I guess this happens when fetch fails to parse the result in the frontend at this line: return response.json().then(jsonResponse => {.
Instead of returning valid JSON, the backend returns a file that starts with "<" (the unexpected token). Your backend responds with an HTML page instead of JSON.
Issue comes from here most likely:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
This basically says that all GET requests should serve index.html. That's why the request doesn't go to apiRouter.get('/'), it stops at the first match, which is the code above. It works on localhost because this code path is inside a conditional that checks NODE_ENV for production.
Not sure why you have it in there, but removing it would solve the issue.
Please try adding the heroku postbuild script to your json file in the root directory as same as the existence of the server.js file, that might help, using in react we must add heroku postbiuld so that the build is saved in the server, and that might not produce an issue,

receive 404 error from post request: postman

I am trying to make a post request from postman but I'm receiving a 404 error: SyntaxError: Unexpected token n in JSON at position 4<br> at JSON.parse.
I have added the Content-Type: application/json header and defined the json body in the raw tab.
This is the url: http://localhost:8000/api/signup.
I can't make this post request nor can I access the application in the browser as I receive cannot GET /api/signup.
How can I fix this?
const User = require('../models/user')
const { errorHandler } = require("../helpers/dbErrorHandler")
exports.signup = (req, res) => {
console.log("req.body", req.body)
// signs up new user
const user = new User(req.body)
user.save((err, user) => {
if(err) {
return res.status(400).json({
err: errorHandler(err)
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
// import routes
const userRoutes = require('./routes/user')
// app
const app = express()
// connect db - first arg is url (specified in .env)
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
}).then(() => console.log('DB connected'))
// middlewares
// used to save users credentials
// routes middleware
app.use('/api', userRoutes)
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
const mongoose = require('mongoose')
const crypto = require('crypto')
const uuidv1 = require('uuid/v1')
const userSchema = new mongoose.Schema ({
}, {timestamps: true})
userSchema.methods = {
encryptPassword: function(password) {
if (!password) return '';
// hashes password
try {
return crypto.createHmac('sha1', this.salt)
} catch (err) {
return ''
module.exports = mongoose.model("User", userSchema)
const express = require('express')
const router = express.Router()
const { signup} = require('../controllers/user')
router.post('/signup', signup)
module.exports = router
404 means NOT Found,
May be your URL or Method is wrong
Here is what you can try to diagnose:
Check if server is running
Check the port and URL you are accessing.
Check the postman method POST and URL.
Check the route, routes file and match it with postman URL
This seems like two different issues, for the POST request, the error seems like there is an invalid string in your JSON payload that your application cannot read and parse.
The second one is mainly due to the route is not found, without looking at your ./routes/user file, it seems like there are two possibilities:
You have a nested route of /user/.... If that is the case, try accessing your api via /api/user/signup instead of /api/signup
You did not create a GET route for you signup path. Normally signup is a POST path instead of GET.
It would be best if you can provide the source code of ./routes/user.js for us to properly answer this.
404 error is an HTTP status code that means that the page you were trying to reach on a website couldn't be found on their server. To be clear, the 404 error indicates that while the server itself is reachable, the specific page showing the error is not.
Make sure that your indexing is correct and your local server is running properly.

Get request with supertest parsing issue

I am using supertest to test get requests to mLab app. If I do a regular GET request with postman I receive this:
{"_id":"5b169a9951573c50d9682d52","text":"First test note","title":"Test1"}
But the response received in the test adds slashes before each quote:
{\\"_id\\":\\"5b169a9951573c50d9682d52\\",\\"text\\":\\"First test note\\",\\"title\\":\\"Test1\\"}
This is my test file:
const server = require("../../app/server");
const request = require("supertest")(server);
describe("routes: index", () => {
test("should respond as expected", async() => {
const app = request("http://localhost:8000");
const response = await app.get("/notes/5b169a9951573c50d9682d52");
expect(response).toEqual("First test note");
This is my server
const express = require('express'); // node module
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = process.env.PORT || 8000;
extended: true
MongoClient.connect(db.testUrl, (err, database) => {
if (err) return console.log(err)
require('./routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
module.exports = app;
I haven't been using supertest myself, but a brief look at your code and documentation immediately shows several issues.
First of all, what you see is what your test framework reports to you - it is a string representation of the json object. It is correct.
What is not correct is how you try to handle the response. Check the documentation:
I think, you may solve the problem by
1) setting the expected type
2) and by accessing the body member of the response
const response = await app.get("/notes/5b169a9951573c50d9682d52").set('Accept', 'application/json');
expect(response.body.text).toEqual("First test note");
I hope, this works.