简体   繁体   English

使用NodeJS Express时将表单数据插入MySQL数据库

[英]Inserting form data into MySQL database when using NodeJS Express

For a school project I need to insert data from a html form into my database. 对于学校项目,我需要将html表单中的数据插入数据库。 The problem is, I never worked with NodeJS, Express, Handlebars or JavaScript before and I cant seem to figure out how it works, I currently have this form in my .hbs file 问题是,我以前从未使用过NodeJS,Express,Handlebars或JavaScript,而且似乎无法弄清楚它的工作方式,我目前在.hbs文件中有此表格

<div class="row">
    <form action="" method="post" class="col s12">
    <div class="row">
        <div class="col s3 offset-s1">
            <label>Sensor Type</label><br>
            <label>
                <input id="combo" class="with-gap" name="sensorType" type="radio"/>
                <span>Temperature & Humidity</span>
            </label><br>
            <label>
                <input id="temp" class="with-gap" name="sensorType" type="radio"/>
                <span>Temperature</span>
            </label><br>
            <label>
                <input id="humid" class="with-gap" name="sensorType" type="radio"/>
                <span>Humidity</span>
            </label>
        </div>
    </div>
    <div class="row">
        <div class="input-field col s3 offset-s1">
            <select id="sensorForest">
                <option value="" disabled selected>Choose your forest</option>
                <optgroup label="The Netherlands">
                    <option value="streekbos">Streekbos Bovenkarspel</option>
                </optgroup>
                <optgroup label="United States of America">
                    <option value="losAngeles">Los Angeles National Forest</option>
                </optgroup>
            </select>
            <label>Forest</label>
        </div>
        <div class="input-field col s3">
            <textarea id="textarea2" class="materialize-textarea" data-length="50"></textarea>
            <label for="textarea2">Enter sensor Location</label>
        </div>
    </div>
    <div class="row">
        <div class="input-field col s6 offset-s1">
            <div class="input-field col s6">
                <input id="latitude" type="text" class="validate">
                <label for="latitude">Latitude</label>
            </div>
            <div class="input-field col s6">
                <input id="longitude" type="text" class="validate">
                <label for="longitude">Longitude</label>
            </div>
        </div>
    </div>
    <div>
        <div class="row">
            <div class="col s12 offset-s1">
                <button class="btn waves-effect waves-light" id="submit">Submit
                    <i class="material-icons right">send</i>
                </button>
            </div>
        </div>
    </div>
    </form>
</div>

Ive also managed to extract the values of the fields in the form using the following script, but I dont think I can use this since I have to use NodeJS Ive还使用以下脚本设法提取了表单中字段的值,但是我不认为可以使用它,因为我必须使用NodeJS

<script>
var submit = document.getElementById("submit");

submit.onclick = function () {
    //var sensorType = document.getElementById("sensorType").value;
    var sensorForest = document.getElementById("sensorForest").value;
    var sensorLocation = document.getElementById("textarea2").value;
    var latitude = document.getElementById("latitude").value;
    var longitude = document.getElementById("longitude").value;

    console.log(sensorForest, sensorLocation, latitude, longitude);
};
</script>

Does anyone know how I'm supposed to send the data to my database or know a good tutorial that explains me how to do it? 有谁知道我应该如何将数据发送到我的数据库,或者知道一个很好的教程向我解释了如何做?

Thank you 谢谢

To connect your NodeJS/ExpressJS application to a database (mongodb, mysql,...) you need an ORM library. 要将NodeJS / ExpressJS应用程序连接到数据库(mongodb,mysql等),您需要一个ORM库。 For your case i suggest Sequelize. 对于您的情况,我建议续集。 All infos at http://docs.sequelizejs.com/ 有关所有信息,请访问http://docs.sequelizejs.com/

no you don't need an ORM library. 不,您不需要ORM库。 You can just use mysql package from npm 您可以从npm使用mysql包

Well before you save anything to a database, you have to get it to your server. 在将任何内容保存到数据库之前,必须先将其保存到服务器。 I recommend using built-in fetch or if you want better browser support use axios , request-promise or superagent . 我建议使用内置fetch axios ,或者如果您想获得更好的浏览器支持, request-promise使用axiosrequest-promisesuperagent All of these packages can be found on npm 所有这些软件包都可以在npm上找到

Client 客户

Underneath your click handler 点击处理程序下方

fetch('http://localhost:3000/sensors', {
  method: 'POST',
  headers: {
    'content-type': 'application/json'
  },
  body: JSON.stringify({
    sensorForest,
    sensorLocation,
    latitude,
    longitude,
  })
})
.then(function (results) {
  return results.json()
})
.then(function (results) {
  console.log('got results', results)
})
.catch(function (ex) {
  console.error(ex)
})

Dependencies 依存关系

npm init -y && npm i --save express body-parser

Server 服务器

const express = require('express')
const { json } = require('body-parser')

const app = express()

const PORT = process.env.PORT || 3000

app.post('/sensors', json(), (req, res, next) => {
  const body = req.body
  // ...save `body` to database
  // use mysql, sequelize, or knex
  res.send(body)
})

app.listen(PORT, () => console.info(`Server listening on port "${PORT}"`))

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

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