I am trying to connect to my backend mongodb 5.0.5 with nodejs express script.
when running the app.js using nodemon it shows your mongodb is connected but on the localhost it keeps on reloading without any error stack trace.
I am using mongoose models in the models as in MVC in nodejs. Not sure why its is not getting run on localhost, it was working fine when last I used these files.
here are my files:
app.js
// imports
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { append } = require('express/lib/response')
const zomatoRoutes = require('./Routes/zomato')
const mongoose = require('mongoose')
// create express server
var app = express()
//listen to a port
app.listen(7878, () => {
console.log('app running on port 7878');
})
app.use(bodyParser.json())
//connect mongodb
mongoose.connect('mongodb://localhost/zomato', () => {
console.log("MongoDB Connected");},
e => console.log(e)
)
// Middleware routes
app.use('/zomato', zomatoRoutes)
app.use(cors())
Model > locations.js
const mongoose = require('mongoose')
const locationSchema = new mongoose.Schema({
name: {
type: String,
required:true
},
city_id: {
type: String,
required:true
},
location_id: {
type: String,
required:true
},
country_name: {
type: String,
required:true
}
})
module.exports = mongoose.model("LocationsModel", locationSchema, "locations")
Controllers > location.js
const { status } = require('express/lib/response')
const Locations = require('../Model/location')
exports.getAllLocations = (req, res) => {
Locations.find().then(
result => {
res.status(200).json({ message: "data fetched successfully", data: result })
}
).catch(error => {
res.send(500).json({ message: "Error in Database", error: error })
})
}
and my routes
zomato.js
const express = require('express')
const Router = express.Router();
const RestaurantController = require('../Controller/Restaurant')
const LocationsController = require('../Controller/Location')
// configure routes
// Restaurants routes
Router.get('/restaurants', RestaurantController.getAllRestaurants)
Router.post('/restaurants/filter/:pageNo', RestaurantController.getRestaurantsByFilter)
// Locations routes
Router.get('/locations', LocationsController.getAllLocations)
module.exports = Router
my Json files
locations.json goes like this:
[
{
"_id": "1",
"name": "ShalimarBhagh, Delhi",
"city_id": "1",
"location_id": "1",
"country_name": "India"
},
{
"_id": "2",
"name": "Janpat, Delhi",
"city_id": "1",
"location_id": "2",
"country_name": "India"
},
{
"_id": "3",
"name": "MSP, Delhi",
"city_id": "1",
"location_id": "3",
"country_name": "India"
}
]
** Updates: I forgot to mention I recently updated to windows10 to make sure my react app works and after this issue is arising, now I created a fresh application with removing mongo and re-installing mongodb still gets me this error in postman Error: read ECONNRESET**
Update I get this stack trace
C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb-
mongoose\node_modules\mongoose\lib\connection.js:797
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri
(C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb-
umongoose\node_modules\mongoose\lib\connection.js:797:32)
Try this instead:
// imports
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { append } = require('express/lib/response')
const zomatoRoutes = require('./Routes/zomato')
const mongoose = require('mongoose')
// create express server
const app = express()
// Middleware routes
app.use(cors())
app.use(bodyParser.json())
app.use('/zomato', zomatoRoutes)
//connect mongodb
mongoose.connect('mongodb://localhost/zomato', () => {
console.log("MongoDB Connected");
const server = app.listen(7878, () => {
console.log('app running on port 7878');
})
server.setTimeout(0) // disable the default time out server mechanism
},
e => console.log(e)
)
Which is:
initialize exprress app
register middlewares
connect to mongo
if connection successful (and only then) - start the application
Also, replace your code
res.status(200).json({ data: 'whatever' })
to:
res.status(200).send({ data: 'whatever' })
There is a chance that your response is not getting back to client, hence - resulting in timeout error. This approach should fix this as well
Hope it will help you with your problem
Localhost is not resolved, though I changed my mongodb to ipv6 using mongod --ipv6 still it does not accept and in stack trace shows isIPV6 : false.
so finally I had to change the using the answer here listen to port using ipv4
//connect to mongoDB
const uri = 'mongodb://localhost:27017/zomato';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
family:4
}
const connectWithDB = () => {
mongoose.connect(uri, options, (err, db) => {
if (err) console.error(err);
else console.log("database connection")
})
}
connectWithDB()
It is working now and fetching data but want to resolve the issue of ipv6 nodejs.
Related
I have a mongodb server setup which on running the below command starts on port 3000
npm run start
I also a graphql server which on running the below command starts at port 4000
npm run start-graphql
the scripts of my package.json is as below
"scripts": {
"start": "nodemon server.js",
"start-graphql": "nodemon graphqlserver.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
server.js
require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_URL);
const db = mongoose.connection;
db.on('error', (err) => console.log(err));
db.once('open', () => {
console.log("Backend Database connected");
});
app.use(express.json({ limit: '2mb'}));
const photosRouter = require('./routes/photos');
app.use('/images', photosRouter)
app.listen(3000, () => {
console.log('Server started at port 3000');
})
graphqlserver.js
const express = require('express');
const path = require('path');
const express_graphql = require('express-graphql').graphqlHTTP;
const { loadSchemaSync } = require('#graphql-tools/load');
const { GraphQLFileLoader } = require('#graphql-tools/graphql-file-loader');
const { addResolversToSchema } = require('#graphql-tools/schema');
const getResolvers = require('./graphql/resolvers');
// GraphQL schema
const combinedSchema = loadSchemaSync(
path.join(__dirname, './graphql/schemas/*.graphql'),
{
loaders: [new GraphQLFileLoader()],
}
);
const schema = addResolversToSchema({
schema: combinedSchema,
resolvers: Object.assign({}, getResolvers())
});
// Create an express server and a GraphQL endpoint
const app = express();
app.use('/graphql', express_graphql({
schema: schema,
graphiql: true
}));
app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
when I call the rest api's normally either through postman or curl it returns the response as expected.
For eg: http://localhost:3000/images returns me an array of objects
But When I want to call (using axios) the same via the graphql server (which is running on port 4000 ),
I get response as null.
I have no clue why this is happening.
Please check the below screenshot for your reference
Note: For better clarity please check the codebase link
https://github.com/yaswankar/G-photos-backend
Any help would be appreciated.
Thanks in advance
Request: Please help by giving an upvote so that it could better reach to those who could help.
Edit:
New Error screenshot
I was able to resolve the main issue by adding the query block inside photos resolver
Query: {
photo: photosContext,
},
The other error was resolved by processing the response instead of sending the raw data to the hyper class
async function getActivePhotos(parent, args, req) {
try {
const activePhotos = await photoService.getActivePhotos(req).then(resp => resp.data.map(item => item)); // Process and mapping data
return activePhotos;
} catch (error) {
// logger.error(__filename + ': Failed to get response for getActivePhotos, err=' + JSON.stringify(error));
return new GraphQLError(JSON.stringify(error));
}
}
I am making a simple test for RESTApi using Node.js, mongodb and express from this article:
MERN Part I: Building RESTful APIs with Node.js and Express
but there is an error somewhere in code i can't locate. The author of article used babel but due to some other error i avoided it. Given below are code files:
App.js
var routes= require('./src/routes/userRoutes').routes
var express= require("express")
var mongoose=require('mongoose')
var bodyParser=require('body-parser')
const app = express();
const PORT=4001
// SET INDEX PAGE
app.get('/',function(req,res){
res.send(`Node and express server running on PORT ${PORT}`);
});
// START SERVER
app.listen(PORT,function(){
console.log(`Your server is running on PORT ${PORT}`);
});
// ESTABLISH ROUTES
routes(app)
// Join Database to API
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/userdb', {
useNewUrlParser:true,
useUnifiedTopology:true
})
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userModel.js : I have commented out the "required" to avoid the Validation Error and see what document is being saved in the collection.
var mongoose = require('mongoose')
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName:{
type:String,
//required:"Enter your name",
},
UserID:{
type:Number,
//required:"Enter User ID:",
},
password:{
type:String,
// reequired:"Enter your password?",
}
});
module.exports={UserSchema}
userController.js:
var mongoose=require('mongoose')
var UserSchema = require("../models/userModel").UserSchema;
const UserModel= mongoose.model("Users",UserSchema)
const addNewUser = (req,res) => {
let newUser= new UserModel(req.body);
newUser.save((err,user) => {
if(err) res.send(err)
else res.json(user)
})
}
module.exports={addNewUser}
userRoute.js:
var addNewUser = require('../controllers/userController').addNewUser;
const routes = (app) => {
// create routes for login/signup/view
app.route('/users')
.get((req,res)=> res.send("Get request successful"))
app.route('/users/:userID')
.put((req,res)=>res.send(`Put Request succesful for ${req.params.donationID}`))
.delete((req,res)=>res.send("delete Request successful"))
.post(addNewUser);
app.route('/done')
.get((req,res)=>{
res.send("Goodbye");
process.exit(0);
});
}
module.exports={routes};
Response recieved when POST request with URI:localhost:4001/users/1?userName=Adnan&UserID=123&password=0000
{
"_id": "5fd0b07b12615110d420a91b",
"__v": 0
}
Expected Output: User Object in JSON
PROBLEM: When I am making the POST request in postman, the postman keeps on sending requests and I do not get any response.
I went through other answers about postman hanging when POST request is made, but could not find a solution to my problem.
GET REQUEST WORKING FINE
Following is the request that I made
{
"title": "This is title",
"description":"This is my first RestfulAPI"
}
I have 3 files Post.js, posts.js, app.js
Post.js
const mongoose = require('mongoose');
//Creating a schema
const PostSchema= mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
})
module.exports=mongoose.model('Posts',PostSchema);
posts.js
const express= require('express');
const router=express.Router();
const Post= require('../models/Post');
router.get('/',(req,res) => {
res.send('We are on posts');
});
router.get('/specific',(req,res) => {
res.send('Specific posts');
});
router.post('/',async (req,res)=>{
console.log(req.body);
const post= new Post({
title: req.body.title,
description: req.body.description
});
try{
const savedPost = await post.save();
res.json(savedPost).status(3000).end();
}catch(err){
res.json({message: err}).status(3000).end();
console.log('Something is wrong');
}
});
module.exports= router;
app.js
const express = require('express');
const mongoose= require('mongoose');
const app= express();
const bodyParser= require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
const postsRoute = require('./routes/posts');
app.use('/posts',postsRoute);
app.get('/',(req,res) => {
res.send('We are on home');
});
mongoose.connect(process.env.DB_CONNECTION,{ useNewUrlParser: true,useUnifiedTopology: true },() =>
console.log('connected to DB!')
);
app.listen(3000);
My console after sending POST request
You would not need .end() after calling res.json(), as you probably want to send the savedPost back to the client.
The express documentation mentions here that
[res.end()] is used to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
You also need to send back the proper HTTP code that ranges from 1xx to 5xx, when working with HTTP. You can read more about them here
Your response should probably look like
res.status(200).json(savedPost);
I'm trying to connect from Nodejs to DialogFlow. I have completed all the steps to configure the user agent, the intent, etc. If I lunch with NODEMON the app, all its ok, but when I send a GET or POST request I get this error:
"UnhandledPromiseRejectionWarning: TypeError: sessionClient.projectAgentSessionPath" and more. But I think the most relevant mistake is this.
The code I used it's the same as the APi docs. I don't know why I get this error.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const dialogflow = require('#google-cloud/dialogflow');
const uuid = require('uuid');
//const sendReq = require('./reqDialogFlow');
async function runSample(projectId = 'helpcenter-qwoj') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'it',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
};
app.get('/', (req, res) => {
res.send({ "hello": "Daniele Asteggiante" })
});
app.post('/api/textAPIE', (req, res) => {
res.send({ "text": "CIAO" });
runSample();
});
app.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
app.listen(PORT);
i had the same error.
i had installed
npm i dialogflow
instead of
npm install #google-cloud/dialogflow
I tried to change the Express Version version with an earlier version 4.17.0 instead 4.17.1.
Now it goes.
change "sessionClient.projectAgentSessionPath" -> "sessionClient.sessionPath"
Found this solution on github:https://github.com/googleapis/nodejs-dialogflow/issues/127
I cannot work out why I would get a query undefined when I know my definitions are correct. graphiQL is picking up my schemes without problems:
Auto complete works fine:
After hitting ctrl+enter all the fields are entered, see above.
Then I execute the query and I'll get:
{
"errors": [
{
"message": "Cannot read property 'query' of undefined",
"locations": [
{
"line": 1,
"column": 3
}
],
"path": [
"allAwards"
]
}
],
"data": {
"allAwards": null
}
}
npm run graphql
"graphql": "nodemon -r dotenv/config --experimental-modules --inspect=[9222] graphql_server.js",
graphql_server.js
import express from 'express'
import pg from 'pg'
import graphqlHTTP from 'express-graphql'
import PAS from 'postgraphile-apollo-server'
import AP from 'apollo-server-express'
const { makeSchemaAndPlugin } = PAS
const { ApolloServer } = AP
const env = process.env.NODE_ENV || 'development'
const dbHost = process.env.DB_HOST
const dbPort = process.env.DB_PORT
const dbName = process.env.DB_NAME
const dbUser = process.env.DB_USER
const dbPwd = process.env.DB_PWD
const dbUrl = dbPwd
? `postgres://${dbUser}:${dbPwd}#${dbHost}:${dbPort}/${dbName}`
: `postgres://${dbHost}:${dbPort}/${dbName}`
const pgPool = new pg.Pool({
connectionString: dbUrl,
})
async function main() {
const { schema, plugin } = await makeSchemaAndPlugin(
pgPool,
'public', // PostgreSQL schema to use
{
// PostGraphile options, see:
// https://www.graphile.org/postgraphile/usage-library/
}
)
const server = new ApolloServer({
schema,
plugins: [plugin],
})
const app = express()
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
})
)
server.applyMiddleware({ app })
app.listen({ port: 4000 }, () => console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`))
}
main().catch(e => {
console.error(e)
process.exit(1)
})
There are 2 rows currently in psql db for awards as well
You should not utilize middleware from both express-graphql and apollo-server in your express application. Because postgraphile-apollo-server works explicitly with ApolloServer, drop express-graphql altogether. Having both middleware is likely to cause unexpected issues since they listen on the same paths.
Apollo has abandoned GraphiQL in favor of GraphQL Playground. If you want to use GraphiQL with Apollo, you can use a package like express-graphiql-middleware.