0
votes

I uploaded my Node backend application on the Nginx server. And the server IP is working properly as well. I am uploading an image using base 64 formats. I am storing an image in the database in the URL format. That is ip/imageName. It is successfully working on the localhost.

For example, http:localhost:8000/imageName <- when I hit it on the browser it is showing image. The same thing which I would try to do with server ip it is not showing.

Here is my image upload code/api in controller file:

exports.editProfileImg = async (req, res) => {
  console.log("req.body.. ", req.body);
  let imagePath;
  let base64Data;

  function myFunction(length, chars) {
    var mask = "";
    if (chars.indexOf("a") > -1) mask += "abcdefghijklmnopqrstuvwxyz";
    if (chars.indexOf("A") > -1) mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (chars.indexOf("#") > -1) mask += "0123456789";
    var result = "";
    for (var i = length; i > 0; --i)
      result += mask[Math.floor(Math.random() * mask.length)];
    return result;
  }
  var randomNumber = myFunction(25, "#aA");
  var data = req.body.profilePic.split(";");
  if (data[0] == "data:image/1") {
    imagePath = "./uploads/" + randomNumber + ".png";
    base64Data = req.body.profilePic.replace(/^data:image\/1;base64,/, "");
  } else if (data[0] == "data:image/*") {
    var base64 = data[2].split(",");
    base64Data = base64[1];
    var data = base64[1].substring(0, 8);
    if (data == "/9j/4AAQ") {
      imagePath = "./uploads/" + randomNumber + ".jpeg";
    } else {
      imagePath = "./uploads/" + randomNumber + ".png";
    }
  } else if (data[0] == "data:image/png") {
    imagePath = "./uploads/" + randomNumber + ".png";
    base64Data = req.body.profilePic.replace(/^data:image\/png;base64,/, "");
  } else if (data[0] == "data:image/jpeg") {
    imagePath = "./uploads/" + randomNumber + ".jpeg";
    base64Data = req.body.profilePic.replace(/^data:image\/jpeg;base64,/, "");
  } else {
    console.log("image invalid");
  }
  fs.writeFile(imagePath, base64Data, "base64", async function (err) {
    if (err) {
      console.log("err: ", err);
      res.json({
        success: false,
        message: "Base64 Image is not converted",
        data: err,
      });
    } else {
      const imageUrlPath =
        "http://198.199.74.223" + imagePath.split("./uploads")[1];

      console.log("imageUrlPath ", imageUrlPath);
      user
        .findOne({ _id: req.body.userId })
        .lean()
        .exec((error, loginUser) => {
          if (loginUser) {
            if (loginUser.profilePic) {
              console.log("old pic ", loginUser.profilePic);
              const getImgName = loginUser.profilePic.split("//");

              if (fs.existsSync("./uploads/" + getImgName[2])) {
                let filePath = "./uploads/" + getImgName[2];
                fs.unlinkSync(filePath);

                user.findByIdAndUpdate(
                  { _id: req.body.userId },
                  {
                    $set: {
                      profilePic: imageUrlPath,
                    },
                  },
                  { new: true },
                  (e1, newUser) => {
                    if (e1) {
                      return;
                    }

                    res.json({
                      code: 200,
                      status: "success",
                      data: newUser,
                    });
                  }
                );
              } else {
                if (loginUser) {
                  user.findByIdAndUpdate(
                    { _id: req.body.userId },
                    {
                      $set: {
                        profilePic: imageUrlPath,
                      },
                    },
                    { new: true },
                    (e1, newUser) => {
                      if (e1) {
                        return;
                      }

                      res.json({
                        code: 200,
                        status: "success",
                        data: newUser,
                      });
                    }
                  );
                } else {
                  res.json({
                    code: 400,
                    status: "err",
                    message: "No user found",
                  });
                }
              }
            } else {
              user.findByIdAndUpdate(
                { _id: req.body.userId },
                {
                  $set: {
                    profilePic: imageUrlPath,
                  },
                },
                { new: true },
                (e1, newUser) => {
                  if (e1) {
                    return;
                  }

                  res.json({
                    code: 200,
                    status: "success",
                    data: newUser,
                  });
                }
              );
            }
          } else {
            res.json({
              code: 400,
              status: "err",
              message: "No user found",
            });
          }
        });
    }
  });
};

In main index.js file:

app.use(express.static(path.join(__dirname, "uploads")));

app.use("/api/user", userRoute);

Here is my nginx configuration:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root/ver/www/html/debate/frontend/build;
    index index.html;

    location /api {
      proxy_pass http://198.199.74.223:8000;
    }
}

I think something is conflicting. Am I mistaken somewhere?

1
Is this the simplest reproduction of this issue or can you still reproduce the issue without the complexity of application code in Node.js? - tbking
@tbking, May I know what things you did not understand? The question is that not able to view my image with the server ip, on local ip, it shows proper. - Jayna Tanawala
Then it is unlikely that something is wrong with the node.js code which writes the file. However that code forms the biggest chunk in your question which may confuse people who are trying to help. - tbking
@tbking, I change my code and specifying you the exact API for image upload for which I am working. Still, you not getting then let me know - Jayna Tanawala

1 Answers

0
votes

You can set like this it's work for me

location / {
  root /path/to/website/public;
  index index.html;
   try_files $uri $uri/ @express; # instead of 404, proxy back to express using a named location block;
}
location @express {
  proxy_pass http://localhost:8080;
}

Please follow this link it's help you. Express + Nginx. Can't serve static files