DEV Community

Shernz
Shernz

Posted on

Express not reached

Hey guys,
I'm trying to send a post request to the node server but it's not able to reach. Can anyone please help me out as to why this is happening?
This is the code for server

const express = require("express");
const app = express();
const mongoose = require('mongoose');
const port = process.env.PORT || 4000;

require('dotenv').config();
app.use(express.json);

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true});

const connection = mongoose.connection;
connection.once('open', ()=>{
    console.log("Mongo db connected successfully")
});

const postsRouter = require("./routes/posts");

app.use("/posts", postsRouter);

app.listen(port, ()=>{
    console.log(`Connected and listening at port ${port}`)
})

And this is for post

const router = require("express").Router();
let posts = require("../blog.model");

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

router.route("/write").post((req, res) => {
    const title = req.body.title;
    const content = req.body.content;
    const date = new Date();

    const newPost = new posts({title, content, date});

    newPost.save()
    .then(() => console.log('Post added!'))
    .catch(err => res.status(400).json("Error" + err));
})
module.exports = router;

Alt Text

Top comments (4)

Collapse
 
shubhamverma profile image
Shubham Verma

Can you share the code?

Collapse
 
shernz profile image
Shernz

I've attached the code

Collapse
 
ishansrivastava profile image
Ishan Srivastava

Hey can you let me know two things, whats the value of port? And secondly if you make a testing route , like GET /test, and return a test JSON, does it work?

Collapse
 
shernz profile image
Shernz

4000 is the port value. And I also tried send() which is resulting the same