I'm having issues with this code, I'm trying to implement search functionality on my angular web page, but when I test this code in postman it just returns "NO USER FOUND WITH USERNAME: undefined". Also on the webpage when I provide the search query it says error 404, not found. Any help? here is the code:
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));
});
Here is the angular part of the code:
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;
});
}
}
and the 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>
I hope somebody can help me solve this issue. Thank you!
You use a query parameter q
to send the search text to the server.
But in the server you try to access this parameter with req.body.q
. You should use req.query.q
to access query parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.