无法通过HTML / JavaScript / Express Node应用发布表单数据

时间:2017-04-12 04:04:03

标签: javascript html node.js mongoose

我正在尝试构建一个应用程序,让我输入有关事件的信息,然后将其固定在地图上。在实际保存信息时,我一开始就陷入困境。当我在Chrome中使用Inspect时,它告诉我它已发布,但数据是空白的。我对这种东西很新,不知道我哪里出错了。

第一个文件是我设置数据库的app.js,一个简单的部分模式等。

第二个文件是我的dashboard.html,它显示地图和表单。我正在尝试onsubmit / javascript的东西,它显示数据而不刷新页面,但理想情况下我希望能够刷新页面并让数据仍然在某处发布。

任何帮助将不胜感激!谢谢! :)

require('dotenv').config({ silent: false });	// Retrieve .env contents

var http = require('http');						// Basic HTTP functionality
var path = require('path');						// Parse directory paths
var express = require('express');				// Provide static routing to pages
var app = express();
var Router       = require('router')
var router = Router()

var server = http.Server(app);
var port = 8080;
var app = setupExpress();

// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password@ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);

//Get the default connection
var db = mongoose.connection;

// Start server on port 8080
// localhost:8080
server.listen(port);

//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));


//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
    eventName          : String,
    eventType          : String
});
var Event = mongoose.model('Event', EventSchema);

app.post('/dashboard', function(req, res) {
  res.json(req.body); // req.body is your form data
});

app.post('/dashboard', function(req,res){
var content = new Event({
  eventName : req.body.eventName,
  eventType : req.body.eventType
}).save(function(err,doc){
    if(err){
      return handleError(err);
    } else {
      console.log('your form has been saved');
    }
  })
});

function setupExpress()
{
	// Set default path for views and public
	var viewsDir = path.join(__dirname, 'views');
	var publicDir = path.join(__dirname, 'public');

	app.use(express.static(publicDir));

	// Root page is login form
	app.get('/', function(req, res)
	{
		res.sendFile('views/index.html', { root: '.' });
	});

	// Once logged in, home page is dashboard
	app.get('/dashboard', function(req, res)
	{
		res.sendFile('views/dashboard.html', { root: '.' });
	});

	// Redirect to error page if there's an issue
	app.use(function(err, req, res, next)
	{
		console.log(err.stack);
		res.status(err.status || 500);

		res.sendFile('/views/error.html', { root: '.' });
	});

	return app;
}
<!DOCTYPE html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Web browser tab title -->
  <title>App</title>

  <!-- Bootstrap Core CSS -->
  <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <!-- MetisMenu CSS -->
  <link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
  <!-- Custom CSS -->
  <link href="../css/sb-admin-2.css" rel="stylesheet">
  <!-- Morris Charts CSS -->
  <link href="../vendor/morrisjs/morris.css" rel="stylesheet">
  <!-- Custom Fonts -->
  <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

  <script type="text/javascript"
          src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  <script type="text/javascript"
          src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>


  <title>App Tester</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <style>
     #map {
      height: 400px;
      width: 100%;
     }
  </style>
</head>

<body>
  <div id="wrapper">
    <div id="page-wrapper">
      <div class="row">
          <div class="col-lg-8"  style="margin-top: 30px">
            <div class="panel panel-default">
              <div class="panel-heading text-center">
                <i class="fa fa-map-marker fa-3x"> Add Event</i>
              </div>
              <div class="panel-body">
                <div class="col-lg-6">
                  <form id="eventForm" method="post" onsubmit="return false">
                    <div class="form-group">
                      <label for="eventName">Event Name</label>
                      <input type="text" class="form-control" id="eventName" placeholder="Event name">
                    </div>
                    <div class="form-group">
                      <label for="eventType">Type</label>
                      <select class="form-control" id="eventType">
                        <option>Study Group</option>
                        <option>Food</option>
                        <option>Meeting</option>
                        <option>Danger</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label for="eventLocation">Location</label>
                      <select class="form-control" id="eventLocation">
                        <option>Location 1</option>
                        <option>Location 2</option>
                        <option>Location 3</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label for="eventNotes">Event Notes</label>
                      <textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
                    </div>
                    <div class="text-center">
                      <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                  </form>
                </div>

                <div id="confirm"><div>

                <script type="text/javascript">
                  var txt = document.getElementById("eventName");

                  document.getElementById("eventForm").addEventListener("submit", confirmdata);

                  function confirmdata(event) {
                    event.preventDefault();
                    var eventName = txt.value;

                    document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';

                  }
                </script>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</body>

1 个答案:

答案 0 :(得分:0)

您应该使用body-parser将您的数据帖子从客户端更改为json

var bodyParser = require('body-parser')
app.use(bodyParser.json())

您可以通过req.body

获取json数据