2

I am trying to connect my node app with MongoDB. The code seems to execute as I get the output Server is running on port 5000 MongoDB database connection established successfully on the terminal But when I try to post get from insomnia it takes about two minutes before I get the error Error: Server returned nothing (no headers, no data)

const express = require('express');
//const bodyParser = require('body-parser');
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());

const uri = process.env.ATLAS_URI;

mongoose.connect( uri, {useUnifiedTopology: true, useNewUrlParser: true}, () => { console.log("MongoDB database conection established successfully")}).catch(err => console.log(err));

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

//emitter.setMaxListeners();

app.listen(port, () => {
    console.log('Server is running on port : ' + port);
});

I am following a tutorial and these are the other files I have exercise.model.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const exerciseSchema = new Schema({
    username: {type: String,required: true},
    description: {type: String,required: true},
    duration: {type: Number,required: true},
    date: {type: Date,required: true},
    },
{
    timestamps: true,
});


const Exercise = mongoose.model('Exercise', exerciseSchema);

module.exports = Exercise;

exercises.js

const router = require('express').Router();
let Exercise = require('../models/exercise.model');

router.route('/').get((req, res) => {
  Exercise.find()
    .then(exercises => res.json(exercises))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {
  const username = req.body.username;
  const description = req.body.description;
  const duration = Number(req.body.duration);
  const date = Date.parse(req.body.date);

  const newExercise = new Exercise({
    username,
    description,
    duration,
    date,
  });

  newExercise.save()
  .then(() => res.json('Exercise added!'))
  .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

users.js

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((req,res) => {
        User.find()
        .then(users => res.json(users))
        .catch(err => res.status(400).json('Error: ' + err));
    });

router.route('/add').post((req,res) => {
    const username = req.body.username;

    const newUser = new User({username});

    newUser.save()
    .then(() => res.join('User added!'))
    .catch(err => res.status(400).json('Error: ' + err));
})

module.exports = router;

user.model.js

const mongoose = require('mongoose');

    const Schema = mongoose.Schema;

    const userSchema = new Schema({
        username: {
            type: String,
            required: true,
            unique: true,
            trim: true,
            minlenght: 3
        },
    },{
        timestamps: true,
    });


    const User = mongoose.model('User', userSchema);

module.exports = User;

I also get Cannot GET / when I go to http://localhost:5000 on my browser and in the inspector errors it says Refused to load the image 'http://localhost:5000/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback. This may be a lot but I am trying to learn how to connect backend with front end and would appreciate it if someone can guide me. Thank you in advanced.

m.Mig
  • 21
  • 2
  • 7
  • https://www.youtube.com/watch?v=7CqJlxBYj-M this tutorial? I'm following the same tutorial ran into the same problem. – demiculus May 22 '20 at 14:28

3 Answers3

0

The problem seems to be CORS related. This means that the express API you have created, will not accept calls from other domains and expects the interaction to come from the same application. As you are are using insomnia, which is a separate desktop app or something, express will block access to routes. This is the default behavior.

You need to grab the CORS middleware and set up your routes as needed. Just follow the docs.

A quick test to allow all access:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/users', (req, res) => {...
...
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104
0

Ther is an other method to add CORS

app.use(function (req, res, next) {
    //Enabling CORS
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, 
    Accept, x-client-key, x-client-token, x-client-secret, Authorization");
    next();
});
Sohail Ahmad
  • 7,309
  • 5
  • 27
  • 46
0

I'm also going through the same tutorial: https://www.youtube.com/watch?v=7CqJlxBYj-M

The problem is with app.use(express.json());

Comment that out and it'll work fine. But then you won't be able to parse JSON data when you're doing post requests. I'm not sure why express.json() doesn't work.

But either way you can use Body-Parser to solve that problem. First user npm i body-parser to install it to your package manager in your backend folder. Then copy the below code to your index.js

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

add this code and you'll be fine. This answer gives a detailed explanation of express.json & body-parser.

express.json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object.

I recommend using body-parser (it is an NPM package) to do the same thing. It is developed by the same peeps who built express and is designed to work with express. body-parser used to be part of express.

Community
  • 1
  • 1
demiculus
  • 1,243
  • 1
  • 12
  • 32