Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
```
var express = require("express");
var cors = require("cors");
var mongoClient = require("mongodb").MongoClient;

var connectionString = "mongodb://127.0.0.1:27017";

var app = express();
app.use(cors());
app.use(express.urlencoded({
  extended:true
}));
app.use(express.json());

app.get("/getusers", (req, res)=>{
  mongoClient.connect(connectionString, (err, clientObj)=>{
    if (!err) {
      var database = clientObj.db("reactdb");
      database.collection("tblusers").find({}).toArray((err, documents) => {
          if (!err) {
            res.send(documents);
          }
        })
    }
  })
});

app.post("/registeruser", (req, res)=>{
  var userdetails = {
    UserId: req.body.UserId,
    UserName: req.body.UserName,
    Password: req.body.Password,
    Age: parseInt(req.body.Age),
    Mobile: req.body.Mobile,
    Subscribed: (req.body.Subscribed === "true")?true:false
  };
  mongoClient.connect(connectionString,(err, clientObj)=>{
    if(!err){
      var database = clientObj.db("reactdb");
      database.collection("tblusers").insertOne(userdetails,(err, result)=>{
        if(!err){
          console.log("Record Inserted...");
          res.redirect("/getusers");
        }
      })
    }
  })
})

app.listen(4000);
console.log("Server Started : http://127.0.0.1:4000");

```

What I have tried:

I was trying to build a simple MERN stack application and while building that I wanted to create my own API, so I created a server folder and made a file with the name api.js inside it. Which is given above and tried to connect it with my mongodb database but when I type http://127.0.0.1:4000/getusers and hit enter it keeps loading and doesn't show anything. I tried to use postman also, but nothing happened, it keeps loading.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900