繁体   English   中英

我的搜索功能在 angular 和 node.js 中不起作用

[英]My search functionality isn't working in angular and node.js

我在使用此代码时遇到问题,我试图在我的 angular web 页面上实现搜索功能,但是当我在 postman 中测试此代码时,它只返回“未找到用户名:未定义的用户”。 同样在网页上,当我提供搜索查询时,它显示错误 404,未找到。 有什么帮助吗? 这是代码:

let conn = new mysqli({
    Host: 'localhost', 
    post: 3306, 
    user: 'root', 
    passwd: '', 
    db: 'registracija'
}); 


let db = conn.emit(false, '');
app.get('/search',(req,res)=>{
    const query = req.body.q;

    //const sql = `SELECT * FROM users WHERE username LIKE '%${query}%'`;

    /*db.query(sql, (error, results)=>{
        if (error){
            res.status(500).send({error:'Error executing SQL query'});
        }
        else {
            res.send(results);
        }
    });*/

    db.table('users').filter({username: query}).withFields(['username','password']).get()
    .then(user =>{
        if (user){
            res.json({user});
        }
        else{
            res.json({message:`NO USER FOUND WITH username: ${query}`});
        }
    }).catch(err => res.json(err)); 
});

这是代码的 angular 部分:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  query = '';
  results: any = [];
  constructor(private http: HttpClient) { }

  ngOnInit(): void {
  }

  search(){
    this.http.get('/search', { params: { q: this.query}}).subscribe(results => {
      this.results = results;
    });
  }

}

和 html:

<input [(ngModel)]="query" placeholder="Enter search query" />
<button (click)="search()">Search</button>

<!-- create a container to display the search results -->
<div *ngIf="results.length">
  <h3>Search Results</h3>
  <ul>
    <!-- use the ngFor directive to iterate over the search results -->
    <li *ngFor="let result of results">
      {{ result.username }}
    </li>
  </ul>
</div>

我希望有人能帮我解决这个问题。 谢谢!

您使用查询参数q将搜索文本发送到服务器。

但是在服务器中,您尝试使用req.body.q访问此参数。 您应该使用req.query.q来访问查询参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM