Loading localhost:3001 which worked for me before, stopped working for me all of a sudden. I am not seeing anything wrong on the code and I am getting server started message as well when run the server. But localhost:3001 doesn't seem to be loading.
here is the code -
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const cors = require('cors');//to have this api accessed by multiple domains
const dotEnv = require('dotenv');
dotEnv.config();
const app = express();
//middleware
app.use(cors);
app.use(express.json());
const typeDefs = gql`
type Query {
greetings: String
}
`;
const resolvers = {};
const apolloServer = new ApolloServer({
typeDefs,
resolvers
});
apolloServer.applyMiddleware({app, path: '/graphql'});
const PORT = process.env.PORT || 3000;
app.use('/', (req,res, next) => {
res.send({message: 'Hello Sumesh'});
});
app.listen(PORT, () => {
console.log(`Server listening on PORT: ${PORT}`);
console.log(`GraphQL Endpoint: ${apolloServer.graphqlPath}`);
});
Here is the terminal output when the server running -
Problem is with your cors middleware statement. It should be:
app.use(cors());
instead of
app.use(cors);
Related
enter image description here I need to know what's the problem. I am not getting the message on console for establishment of Mongodb database connection.
Here is a link to the error picture. https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link
server.js file
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
// debugger
var uri; // Define outside
if(process.env.ATLAS_URI){
uri = process.env.ATLAS_URI; // Assign inside the block
}
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, ()=> {
console.log(`Server is running on port: ${port}`);
});
.env file
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
I tried to debug the code and found that uri was coming as undefined. Do I need to convert the password in ATLAS_URI to some other format?
The .env file must be located in the root folder of your project. And you should run the project from the root folder. Therefore:
Example 1
server.js
.env
Run it with node ./server.js
Example 2
src
|-server.js
.env
Run it with node ./src/server.js
You did one mistake in .env file
you did
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
But you have to use url of atlas as an string
ATLAS_URI = "mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority"
The .env file must be located on the root folder and you must include it in the file where ever you need it at the very top.
and a few changings you just need to do and the things are good to go.
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.ATLAS_URI)
.then(() => {
console.log("DB connection successful")
app.listen(port, () => {
console.log(`app listening on port ${port}`);
})
})
.catch((err) => {
console.log(err)
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
I am not getting why you just create a var for ATLAS_URI. Just keep the code simple and neat and clean.
The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})
I create a web site with MERN stack and deploy it with heroku. the DB connected to mongodb atlas. work great locali but when i try to connect the DB with heroku its working only when my backend on vsCode connected to the DB.
the error notes is:
*Failed to load resource: net::ERR_CONNECTION_REFUSED
*Uncaught (in promise) Error: Network Error
at e.exports (createError.js:16:15)
at XMLHttpRequest.g.onerror (xhr.js:117:14)
this is my code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const usersRouter = require("./routes/usersRout");
const authRouter = require("./routes/auth");
const carsRouter = require("./routes/carsRout");
const bizRouter = require("./routes/bizRout");
mongoose
.connect(
process.env.MONGODB_URI ||
"mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority"
)
.then(() => {
console.log("connected to mongo");
})
.catch((err) => {
console.log("faild to connect to mongo server", err);
});
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("noto-front/build"));
}
app.use("/api/users", usersRouter);
app.use("/api/auth", authRouter);
app.use("/api/cars", carsRouter);
app.use("/api/biz", bizRouter);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`connected on port ${PORT}`);
});
my config vars on heroku:
MONGODB_URI - mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority
NODE_ENV - production
what am i doing wrong?
I wrote this code in my node app
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
//middleware
app.use(cors);
//access req.body
app.use(express.json());
app.get("/", async (req, res) => {
try {
res.json("response from server");
// const allCompanies = await pool.query("SELECT * FROM COMPANIES");
// res.json(allCompanies.rows);
} catch (error) {
console.log(error.message);
}
});
const port = 1337;
app.listen(port, () => {
console.log(`Server is starting on port ${port}`);
});
In my terminal it says its running on 1337 however when i try to connect to postman it leaves me hanging? never had this problem before.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
The problem was that you were not calling the cors function on your app.use middleware.
If you change the code to
app.use(cors());
It should work.
Express Documentation
This is my server.js -
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
Router (feedbackRouter.js)-
const express = require("express");
const router = express.Router();
router.post("/feedback", (req, res) => {
const feedbackData = req.body;
try {
console.log(feedbackData);
res.send(feedbackData);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = router;
When I make an API call from the frontend(React) or Postman, the req.body gives me undefined and I don't see the content from the request anywhere.
The API call gives me status code of 200 in Postman.
Any idea what might be wrong here? Thanks in advance.
Add app.use(express.json()) to your Code.
Server.js:
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
About express.json() method and its options:
https://expressjs.com/en/5x/api.html
You didn't use any body-parsers, they use to process the body of an request, documentation:
http://expressjs.com/en/resources/middleware/body-parser.html
Postman Request & Response: