[英]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.