2017-03-23 2 views
0

これはDBが接続されている私のserver.jsファイル、次のとおりです。Node.JS + mySQL - > ajax呼び出しを行い、server.jsのデータにアクセスするには?

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上のデータは、私が明らかに(値を挿入する)クエリを作りたいということ取得した後どのように私はデータを得るのですか?

+0

mhm?何か案は? – Caitiff

答えて

0

これは私が私のプロジェクトの1のためにそれをやった方法です:

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)); 
}) 
}) 

ですから、私はapp.post定義されていると私は私のURLを打っています見ることができ、あなたのserver.jsに

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

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

がこれらを含めるようにしてください。次に、データを格納するSQLクエリを記述します。

+0

興味深い。ありがとうございました。私はこれを試してみます – Caitiff

+0

うまくいくと思っています... –

+0

req.body.nameは定義されていません – Caitiff

関連する問題