Node.JS + mySQL - >如何进行ajax调用并访问server.js上的数据?

时间:2017-03-23 09:27:26

标签: javascript mysql ajax node.js

所以这是我的server.js文件,其中db连接到:

var app = require('express')();
var mysql = require('mysql');
var db = mysql.createConnection({

    host: 'localhost',
    user: 'root',
    password: '',
    database: 'user_data',
    port: 3306
});
db.connect();

app.get('/', function (req, res) {
    res.sendFile(__dirname + "/start.html");
});

app.listen(3000);

所以我想制作一个类似注册表格的东西,你输入你的用户名和密码。然后,在单击提交按钮后,用户名和密码应该直接进入mySQL数据库。显然,我需要一个将数据发送到该服务器的ajax调用,但我不知道如何在server.js上访问它。

$("button#submit").click(function () {
      $.ajax({
           'url': 'http://localhost:3000',
           'type': 'post',
           'data': {
                'username': $("#usr").val(),
                'password': $("#pwd").val()
           },
           'success': function (data) {
                alert('Data: ' + data);
           }
        });
  })

在server.js上获取数据后,我显然想要查询(插入值),但如何获取数据?

1 个答案:

答案 0 :(得分:0)

这就是我为我的一个项目做的事情:

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Contact Form</title>

</head>
<body>
<div id="contact">
    <h1>Send an email</h1>
    <form action="/myaction" method="post">
        <fieldset>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" placeholder="Enter your full name" />

            <label for="location">Location:</label>
            <input type="text" id="location" name="location" placeholder="Enter your location" />

            <input type="submit" value="Send message" />

        </fieldset>
    </form>
</div>
</body>
</html>

现在,当用户点击提交/ myaction时,url会命中。

db.connect(function(err,connection){
    app.post('/myaction',function(req,res){
    console.log(req.body);

     var employee={name:req.body.name,location:req.body.location}

    db.query('INSERT into employees SET ?',employee,function(err,res){
    if(err){
        throw err;
    }
        else{
        console.log(res);

    }


        })
   res.send(JSON.stringify(req.body));
})
})

确保将这些内容包含在server.js

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

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

所以你可以看到我已经定义了app.post而且我正在点击我的网址。然后我们简单地编写一个sql查询来存储数据。