0

I am building a backend in the MEAN stack and have come across an issue. The point of the app is simple: Upload a file and it saves it to the server. However, I am stumbled upon a problem. The code breaks and throws the following error in the console when I hit the "Submit" button:

<h1>photo is not defined</h1>
<h2></h2>
<pre>ReferenceError: photo is not defined
    at \routes\index.js:32:3
    at Layer.handle [as handle_request] (\node_modules\express\lib\router\layer.js:95:5)
    at next (\node_modules\express\lib\router\route.js:131:13)
    at \node_modules\express-jwt\lib\index.js:112:9
    at \node_modules\jsonwebtoken\index.js:98:18
    at process._tickCallback (node.js:355:11)</pre>

The following is my angularApp.js file:

app.factory('photos', ['$http', 'auth', function($http, auth){
  var o = { photos: [] };
  o.create = function(photo) {
    return $http.post('/photos', photo, {
      headers: {Authorization: 'Bearer '+auth.getToken()}
    }).success(function(data){
      o.photos.push(data);
    }).error(function(a) {
      console.log(a);
    });
  };
  return o;
}]);
app.controller('MainCtrl', [
'$scope',
'photos',
'auth',
function($scope, photos, auth){
  $scope.photos = photos.photos;
  $scope.addPhoto = function(){
    photos.create();
  };
}]);

index.ejs code:

<form ng-submit="addPhoto()">
  <label for="exampleInputFile">File input</label>
  <input type="file" id="exampleInputFile">
  <button type="submit" class="btn btn-primary">Post</button>
</form>

And here is routes\index.js

router.post('/photos', auth, function(req, res, next) {
  var dirname = require('path').dirname(__dirname);
  var filename = req.files.file.name;
  var path = req.files.file.path;
  var type = req.files.file.mimetype;

  var read_stream = fs.createReadStream(dirname + '/' + path);
  var conn = req.conn;
  var Grid = require('gridfs-stream');
  Grid.mongo = mongoose.mongo;
  var gfs = Grid(conn.db);

  var writestream = gfs.createWriteStream({
    filename: filename
  });
  read_stream.pipe(writestream);

  photo.save(function(err, photo){
    if(err){ return next(err); }

    res.json(photo);
  });
});

What I have understood is that the code breaks running the o.create function, but I am not sure why it's unable to find photo, when that's one of the function arguments.

1 Answer 1

1

With the code you've posted for routes/index.js, the line

photo.save(...

is using a variable photo that was not previously defined in the current or any parent scope.

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.