簡體   English   中英

如何使用Node.js從Node.js發送和獲取JSON數據到HTML

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

我目前正在嘗試建立簡單的在線論壇,人們可以發表評論; 但是,我不確定我寫的是正確的方法。 通過選擇type =“POST”提交表單后會自動調用Ajax嗎?

我也不確定我是否在路線文件中編寫正確的程序。

這是我的代碼。

<!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>

這是我的路線文件

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;

這是我的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;

謝謝:)

我建議postman chrome插件,它是一個寧靜的api客戶端,你首先通過它調用api,然后如果api執行完美,你可以寫ajax post else。

表單提交時不會自動調用您的ajax帖子。 但是,這就是說,瀏覽器確實將post發送到表單標記中的指定端點。

如果您需要在發布帖子時自動顯示注釋,那么您可以在腳本中使用注釋的代碼塊。

另一種方法是做以下事情....

$(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