为什么我无法在 Nodejs-msnodesqlv8 应用程序中使用 AJAX 发帖?

问题描述 投票:0回答:0

我在 Nodejs 中使用 msnodesqlv8 包连接到 SQL 服务器数据库。当然,我安装了这个包,我已经在服务器上有一个 SQL 数据库。我使用了连接所需的选项并成功检索了记录。 首先,我的 app.post 代码是:

const express=require('express');
const app=express();
const sql = require('msnodesqlv8');
const bodyParser = require('body-parser');


const connString="Driver={SQL Server Native Client 11.0};Server=myserver;Database=myDB;Uid=muUid;Pwd=myPwd;" 


app.post('/persons',  (req, res) => {
   const formData = req.body;
    try {
        console.log("Posting"); 
        // Create a new person record in the database
        const query=`INSERT INTO persons (name, age, gender) VALUES (${formData.name}, ${  
        formData.age}, ${formData.gender})`;
        console.log(`${formData.name}, ${formData.age}, ${formData.gender} will be written.`);
        sql.query(connString, query,(err,rows)=>{
        
        res.send(rows);
    });  
      
    } catch (err) {
      
      res.send(err);
    }
  });

HTML代码:

<form id="newRecform"> 
                <div class="row">
                  <div class="form-group col-md-6">      
                    <label for="name">Name:</label>
                    <input class="form-control" type="text" name="name" id="name" required>
                  </div>
                  <div class="form-group col-md-2">
                    <label for="age">Age:</label>
                    <input class="form-control" type="number" name="age" id="age" required>
                  </div>
                </div>
                <div class="row">
                    <div class="form-group col-md-4">
                      <label for="gender">Gender:</label>
                      <select class="form-control" name="gender" id="gender" required>
                        <option value="">-- Select gender --</option>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                        <option value="Other">Other</option>
                      </select>
                    </div> 
                 </div>   
                <br><br><br>
                <button class="btn btn-info btn-sm col-md-2" style="border-radius: 3px;" type="submit">Add Patient</button>
                </form>`

AJAX 邮政编码:

$("#newRecform").on("submit", function (e) {
              e.preventDefault();
              $.ajax({
                  url: 'http://localhost:5001/persons',
                  type: 'POST',
                  data: $(this).serialize() ,
                  success: function (data) {
                      alert('New Record added successfully!')
                  }
                  , error: function (jqXHR, textStatus, err) {
                      alert('Error ' + textStatus + ', err ' + err)
                  }
              });
        });

当我提交表单时,它从不执行 app.post。即使是“console.log”命令在邮政编码中也不起作用

node.js sql-server ajax post connection
© www.soinside.com 2019 - 2024. All rights reserved.