Search code examples
node.jsangularmean-stackimage-uploadingimagesource

Node Js Server Images working only on local


I am using this code with an application with Node js (and angular 6) to read pictures:

Nodejs server file :

    ....
var express = require('express');
var path = require('path');
var app = express();
..
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const fileUpload = require('express-fileupload');
    const cors = require('cors');


    // view engine setup
     app.set('uploads', path.join(__dirname, 'uploads'));
    app.set('view engine', 'jade');

    app.use(cors());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(fileUpload());
    app.use('/uploads', express.static(__dirname + '/uploads'));


    app.post('/upload', (req, res, next) => {
      console.log(req);
      let imageFile = req.files.file;

      imageFile.mv(`${__dirname}/uploads/${req.body.filename}.jpg`, function(err) {
        if (err) {
          return res.status(500).send(err);
        }

        res.json({file: `uploads/${req.body.filename}.jpg`});
      });

    })

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      const err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });

    app.listen(8888, () => {
      console.log('8888');
    });

this code is working on local to read pictures. example: http://localhost:8888/uploads/02.jpg

But when deploying this code on server I can't read the files. example: http://www.mywebsite.com/uploads/image.jpg (image existing)

what I need to do to make this code working on the online website?

Thank you.


Solution

  • in remote server,

    sudo chomd -R 777 your_project_folder
    

    try it, My guess is that permission issue or folder for image is not created.

    so, after check error log, if image folder is not created,

    first, you should create it, second, typing this script. it is script that give full permission to all directory of project