Apócrifo
Apócrifo

Reputation: 53

Search documents from MongoDB with Angular

I am trying to do a bar search to search users from a collection in MongoDB with Angular. I already did the function in the server side and it's working with Postman, but in the client side i am getting this error: "Http failure response for http://localhost:3800/api/find/: 0 Unknown Error"

this is my code on the server side

    function findUser(req, res) {
  let params = req.body;
  User.find(
    { 
     $or: [
             {nick : new RegExp(params.word, 'i')},
             {name : new RegExp(params.word, 'i')}
           ]
     }, function (err, docs) {
    return res.json(docs);
});

and the route

api.post('/find', md_auth.ensureAuth, UserController.findUser);

this is my code on the client side

user.service

findUser(word): Observable<any>{
        let params = JSON.stringify(word);
        let headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', this.getToken());
    console.log(params);
        return this._http.post(this.url+'find/', params, {headers: headers});

    }

user controller

  @ViewChild('word') wordS:ElementRef;

  findUser(){
    this.word = this.wordS.nativeElement.value;
    console.log(this.word);
    this._userService.findUser(this.word).subscribe(
      response => {
        console.log(this.word);
        console.log(response);
      }, error => {
        var errorMessage = <any>error;
        console.error(errorMessage);
      }
    )
  }

and html (view)

  <form class="form-inline">
    <input #word class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
    <button class="btn btn-outline-success my-2 my-sm-0" (click)="findUser()" type="submit">Search</button>
  </form>

Upvotes: 0

Views: 483

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

JSON.stringify() doesn't return an object. It returns a string.

The server-side function is looking for a property called word in the request body.

If you post an object in your user.service instead of just a string...

...,
return this._http.post(this.url+'find/', { word: params }, headers);

Your function should work. However, you don't really need to call JSON.stringify if you're already passing a string to your service method.

Alternatively, if you're using a reactive form, you can just pass the form.value of your FormGroup instance to your service method, which will be an object, e.g. { word: 'some value' }, which can then be passed as the POST data as-is.

Upvotes: 1

Related Questions