1

I'm trying to use an Angular 2 HTTP GET request to simply connect with a Node/Express backend that responds with a list of the file names in a certain folder using the fs.readdir method.

I set up the Angular 2 request as a service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import './rxjs-operators';

@Injectable()
export class PhotoService {

  constructor (private http: Http) {}

  private photosUrl = '/api/photos';  // URL to web API

  getPhotos() : Observable<string[]> {
    return this.http.get(this.photosUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

and then called this service from a component:

ngOnInit() {
    this.photoService.getPhotos()
                     .subscribe(
                        photos => this.fileList = photos,
                        error => this.errorMessage = <any>error);
}

This is the Node backend (with Express set up as per conventions):

//Photo Service
app.get('/api/photos', function(req, res) {
        fs.readdir('./uploads', function(error, files) {
          if (error) {
            throw error;
          }
          else {
            res.end(files);
          }
        });
});

As seen, the HTTP request calls a GET method to http://localhost:3000/api/photos and the Node backend is supposed to receive that request and send back an array of strings that have the names of files in the 'uploads' folder.

However it does not seem to be working. I think I'm getting confused with the format in which the Node API sends the response and how that works with the Observable type that Angular uses in the service.

1 Answer 1

2

Your Angular 2 code looks good to me. But in your Node backend you should not send data with res.end() (see the documentation). Correct would be res.send(files); or in your case res.json(files); which will also set the right Content-Type header.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.