简体   繁体   English

如何使用Node.js从Node.js发送和获取JSON数据到HTML

[英]How to send and get JSON data from Node.js into HTML using Node.js

I am currently trying to build simple online forum where people can post comments; 我目前正在尝试建立简单的在线论坛,人们可以发表评论; however, I am not sure how I write is correct way to do. 但是,我不确定我写的是正确的方法。 Is Ajax automatically called after the form is submitted by choosing type="POST"? 通过选择type =“POST”提交表单后会自动调用Ajax吗?

I am also not sure if I am writing correct programs in 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 这是我的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 you:) 谢谢:)

我建议postman chrome插件,它是一个宁静的api客户端,你首先通过它调用api,然后如果api执行完美,你可以写ajax post else。

your ajax post is not automatically called upon form submission. 表单提交时不会自动调用您的ajax帖子。 However, this being said, the browser does send a post to the specified endpoint in your form tag. 但是,这就是说,浏览器确实将post发送到表单标记中的指定端点。

If you need to automatically display the comments as the posts are made, then you could use the 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's 
        // post functionality while giving you a chance
        // to handle the form data locally prior to the post

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM