【问题标题】:Image is not displaying from Nginx server图像未从 Nginx 服务器显示
【发布时间】:2020-10-17 03:26:45
【问题描述】:

我在 Nginx 服务器上上传了我的 Node 后端应用程序。服务器 IP 也正常工作。我正在使用 base 64 格式上传图像。我正在以 URL 格式将图像存储在数据库中。即 ip/imageName。它在本地主机上成功运行。

例如,http:localhost:8000/imageName

这是我在控制器文件中的图像上传代码/api:

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",
            });
          }
        });
    }
  });
};

在主 index.js 文件中:

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

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

这是我的 nginx 配置:

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;
    }
}

我认为有些事情是矛盾的。我是不是在哪里弄错了?

【问题讨论】:

  • 这是此问题的最简单重现,还是您仍然可以重现此问题而无需 Node.js 中的应用程序代码的复杂性?
  • @tbking,请问您有哪些不明白的地方?问题是无法使用服务器 ip 查看我的图像,在本地 ip 上,它显示正确。
  • 那么写入文件的 node.js 代码不太可能有问题。但是,该代码构成了您问题中最大的一部分,这可能会使试图提供帮助的人感到困惑。
  • @tbking,我更改了我的代码并为您指定了我正在处理的图像上传的确切 API。不过,你没有得到然后让我知道

标签: node.js nginx nginx-reverse-proxy


【解决方案1】:

你可以这样设置它对我有用

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;
}

请点击此链接,它对您有帮助。 Express + Nginx. Can't serve static files

【讨论】:

  • 我试过了,它开始显示图像。但是面临一个新问题,即通过任何路线并重新加载,它显示无法获取错误
猜你喜欢
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 2020-11-23
  • 2018-05-24
  • 1970-01-01
  • 2015-11-17
  • 2011-07-15
  • 2014-01-16
相关资源
最近更新 更多