从前端将数据插入并更新到数据库

时间:2019-06-26 07:50:22

标签: sql node.js sql-server angular express

我是Web开发的新手。我正在开发角度应用程序。我在前端开发了Angular表单,在后端开发了Node.js和Sql服务器。我需要一些帮助将我的棱角形式连接到sql server数据库。我想将数据从我的角度表单保存到我的sql server数据库中。

版本: 角CLI:8.0.3 节点:10.16.0 操作系统:win32 x64 角度:8.0.1

我尝试使用Restful api使用post and get通过服务器页面插入数据。

当我单击角度形式的提交按钮时,如何将角度形式连接到sql数据库并插入和更新数据。

var express = require("express");
var bodyParser = require("body-parser");
var tediousExpress = require("express4-tedious");
var path = require("path")
var app = express();



// Body Parser Middleware
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

//CORS Middleware
app.use(function (req, res, next) {
    //Enabling CORS 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
    next();
});



app.get('/', function (req, res) {


    var sql = require("mssql");

    // config for your database
    var config = {
        server:'******',
        database: '*******',
        user:'******',
        password: '*****',
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('select * from dbo.contact', function (err, recordset) {

            if (err) 
            console.log(err)

else
            // send records as a response
            res.send(recordset);

        });
    });
});

app.use("/contact", (req, res) => {
    res.sendfile( __dirname + "/src/app/contact/contact.component.html");
  });
  app.use("/product", (req, res) => {
    res.sendfile( __dirname + "/src/app/product/product.component.html");
  });
  app.use("/homepage", (req, res) => {
    res.sendfile( __dirname + "/src/app/home/home.component.html");
  });

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}....`));

<div style="text-align:center">
    <h1 class="well">
      We are available here for you
    </h1>
    <div class="loader" *ngIf="dataloading"></div>

    <div class = "row">
      <div class="column">
          <div class ="container">
          <div class="col-md-5">
          <div class="form-area"> 
          <form role="form" (ngSubmit)="processForm()">
          <br style="clear:both">
          <h3 style="margin-bottom: 50px; text-align: center;">Contact</h3>
          <div class="form-group">
          <input required ngModel name="Name" #FirstName="ngModel" (change)="log(Name)" type="text" class="form-control" id="Name" name="name" placeholder="Name" [(ngModel)]="name" required>
        <div class="alert alert-danger"  *ngIf="Name.touched && !Name.valid" > Name is required.</div>
        </div>

          <div class="form-group">
          <input required  type="email" class="form-control" id="email" name="email" placeholder="Email" [(ngModel)]="email" required>
          <div class="alert alert-danger"  *ngIf="email.touched && !email.valid" > Email is required.</div>
          </div>
          <div class="form-group">
          <input type="phone" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" [(ngModel)]="mobile" required>
          </div>
          <div class="form-group">
          <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" [(ngModel)]="subject" required>
          </div>
          <div class="form-group">
          <textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message max(200)" [(ngModel)]="message" maxlength="140" rows="7"></textarea>              
          </div>
          <hr class="mb-4">
          <button type="button" id="submit" name="submit" class="btn btn-primary btn-lg btn-block" (click)="save(name, email, mobile, subject, message)">Submit</button>
          </form>
          </div>
          </div>
          </div>
````
````contact.component.ts
import { Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {HttpErrorResponse} from '@angular/common/http';
import {Router} from '@angular/router';


@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent {
  title = 'Simple Example Contact-us page using Angular 4';
  public data:any=[]


  constructor(private http: HttpClient){
  }

  save(name, email, mobile, subject, message): void {
    this.data['name']= name;
                this.data['email']= email;
                this.data['mobile']= mobile;
                this.data['subject']= subject;
                this.data['message']= message;
    console.log(this.data);
                //add request to send email or into mysql
                this.http.post<any>('/contact1', this.data).subscribe(
        res => {
          console.log(res);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occured.");
        } else {
          console.log("Server-side error occurred.");
        }
      });
   }
}

````


0 个答案:

没有答案