如何使用nodejs和sql作为数据库构建搜索栏?

我已经使用SQL创建了一个数据库,并且有一个基于Angular和nodejs构建的功能网页,该网页已连接到数据库。我需要使搜索栏起作用。我应该如何进行?

xiaoqi176 回答:如何使用nodejs和sql作为数据库构建搜索栏?

在html中创建一个带有keyup事件的输入框:

<input (keyup)="searchData($event)" type="text" class="form-control" placeholder="Search"
          aria-label="Searchbox" aria-describedby="basic-addon1">

在您的.ts文件中添加此功能,该功能将在搜索框的键盘输入时触发:

searchData(event) {
    this.search = event.target.value
    console.log(this.search)
    console.log(this.filter)
    this.empService.searchData(this.search).subscribe((res) => {
      console.log("Filter Response",res);
      if (res) {
        this.employees = res
        if (res.length === 0) {
          this.noData = true
        } else {
          this.noData = false
        }
      }
    },(err) => {
        console.log(err);
        console.log("error")
      })
  }

创建服务以调用节点中的api

searchData(data): Observable<any> {
    return this.http.get(environment.serverUrl + 'searchData?search=' + data).pipe(

      catchError((error: HttpErrorResponse) => throwError(error))
    )
  }

在节点中将api编写为:

let searchData = (req,res) => {
    search = req.query.search
    console.log(search)
    var searchEmployees = `SELECT * FROM employees WHERE (employeeNo LIKE '%${search}%' OR name LIKE '%${search}%' OR email LIKE '%${search}%' OR contact LIKE '%${search}%') AND isDeleted='0' `
    //searchValues = [search,search,search]
    console.log(searchEmployees)
    db.query(searchEmployees,function (errQuery,resQuery) {
        if (errQuery) {
            res.send(errQuery)
        } else {
            res.send(resQuery)
        }
    })
}

根据您的表结构和名称编辑sql查询。

本文链接:https://www.f2er.com/3159719.html

大家都在问