How to send and receive JSON data from Node.js to HTML using Node.js

I am currently trying to create a simple online forum where people can post comments; however I am not sure how I am writing this is the correct way to do it. Is Ajax called automatically after submitting the form by choosing type = "POST"?

I am also not sure if I am writing the correct programs in the routes file.

Here is my code.

<!DOCTYPE>
<html lang="en">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
// $(function(){
//     $("#target").submit(function(event){
//         event.preventDefault();
//         $.post("/users", function(data){
//             $( "#result" ).html( JSON.stringify(data) );
//         });
//     });
// });
//Not sure which way I should use ↑↓

$.ajax({
 type: "GET",
 url: 'http://localhost3000/users',
 data: data,
 dataType: 'json'
})

.done(function(data){
  console.log("GET Succeeded");
  $('#result').html(JSON.stringify); //What should I put after JSON.stringify?
});

 $(function(){
     $("#target").submit(function(event){
      $.ajax({
        type: "POST",
        url: 'http://localhost3000/users',
        data: data,
        dataType: 'json'
      })

      .done(function(data){
        console.log("POST Succeeded");
        $('#result').html(JSON.stringify); //What should I put after JSON.stringify?
      });
    });
 });



</script>
</head>
<body>

<div id="result"></div>

<form action="/users" method="post" id="target">
  Username:<input type="text" name="username">
  <input type="submit" value="Post">
</form>

</body>
</html>

      

Here is my routes file

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var Users = require('../models/users');

var userRouter = express.Router();
userRouter.use(bodyParser.json());

userRouter.route('/')

.get('/users', function (req, res, next) {
        Users.find({}).then(function(user){
          res.json(user)
        }).catch(next);
})

.post(function(req, res, next){
//  res.send("Confirmed");
  Users.create(req.body).then(function(user){
    res.send(user);
  }).catch(next);

  res.json(newUser);
});

module.exports = userRouter;

      

Here is my app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var url = 'my database';
mongoose.connect(url);

mongoose.Promise = global.Promise;

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
});


var routes = require('./router/index');
var userRouter = require('./router/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/users', userRouter);
//Error handler for user
app.use(function(err, req, res, next){
  res.status(422).send({error: err.message});
});

//catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
if (app.get('env') === 'development'){
  app.use(function(err, req, res, next){
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
  });

app.use(function(err, req, res, next){
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
 });

module.exports = app;

      

Thank:)

+3


source to share


2 answers


your ajax post will not be automatically called when the form is submitted. However, as said, the browser sends post

to the specified endpoint in your form tag.

If you need to automatically display comments as posts are created, you can use a commented block of code in your script.



Another approach would be to do the following ...

$(function(){
    $("#target").submit(function(event){
        // add code here to append the form data to the DOM

        // dont call event.preventDefault()

        // doing so will take advantage of the browser 
        // post functionality while giving you a chance
        // to handle the form data locally prior to the post

    });
});

      

0


source


I suggest the postman

chrome plugin , it is a calm api client, you first call the api through it and then if the api works perfect you can write an ajax else message.



0


source







All Articles