0

I am new nodejs coder. In my study, I want to display data in the browser after saving data in mongodb collection.

I am able to save a data in mongodb, but can't show or dipslay data in browser as I plan it to be

enter image description here

After submit, i can save the data in DB, but I would want to either

  1. display in browser the MOST RECENT (based on date) saved/inserted data in DB or

  2. the temperature gotten from the source website

This is the code snippet

const express = require('express');
const dotenv = require("dotenv").config();
const address = process.argv[2];
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const app = express();

//INSERT TO MONGO DB
//connect to mongo db
mongoose.connect('mongodb://localhost/weathertest2');
mongoose.Promise = global.Promise;


//create weather schema
const WeatherSchema = new Schema({
    location:{
        type: String
    },
    temperature:{
        type: String
    },
    observationTime:{
        type: String
    }

});

const Weather = mongoose.model('weather', WeatherSchema);

// post request
app.post('/new', function(req, res){
    new Weather({
        location    : req.body.location,
        temperature: req.body.temperature,
        observationTime   : req.body.observationTime                
    }).save(function(err, doc){
        if(err) res.json(err);
        else    res.send(req.body.location);
    });
});
 

// listen for request
app.listen(process.env.port || 9000, function(){
    console.log('now listening for  testing request');
});
app.use(express.static('public'));
1
  • res.send(req.body.location) is called after submission, it should show your location data in response. in case you want to show this data use template engine such as ejs, pug, handlebarjs etc Commented Sep 22, 2020 at 12:04

1 Answer 1

0

There are couple of things:-

  1. When you open a url in browser its a GET request (read more on HTTP methods)
  2. In your code there is no Get method (atleast not in the one you shared)
  3. You need a Frontend to consume this POST API and return result. 4) If you don't want Frontend, You can have GET method and redirect to it once saving in Mongo is done in POST method (this is for learning, and can be used if use case)
Sign up to request clarification or add additional context in comments.

2 Comments

i have a simple .html file for frontend
you will need javascript to consume API and render the response, or use a template engine like ejs, pug etc OR go for framework/libraries like Angular, ReactJs (If you are not familiar with any google it, you will get plenty of resources)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.