簡體   English   中英

如何從 HTML 調用 NodeJS function?

[英]How to call a NodeJS function from HTML?

我正在嘗試創建一個 function,它將一個新文件添加到 AWS 中的 S3 存儲桶中。 function 在 NodeJS 中工作。

const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});

// call S3 to retrieve upload file to specified bucket
const file = "file.png";
const uploadParams = {Bucket: "uploads", Key: '', Body: ''};

const fs = require('fs');
const fileStream = fs.createReadStream(file);
fileStream.on('error', function(err) {
  console.log('File Error', err);
});
uploadParams.Body = fileStream;
const path = require('path');
uploadParams.Key = path.basename(file);

s3.upload (uploadParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } if (data) {
    console.log("Upload Success", data.Location);
  }
});

我現在要做的是獲取此代碼並使其在 HTML 中上傳文件時執行。我有一個簡單的 HTML 腳本,用戶可以在其中上傳文件,我希望在按下提交按鈕時執行上述代碼。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <form action="javascript:loadAPI(document.getElementByID('fileUpload'))">
      <label>Upload a file to AWS S3</label>
      <input type="file" id="fileUpload" name="filename">
      <input type="submit">
    </form>
    <script type="text/javascript" src="apiFunction.js">
  </script>
  </body>
</html>

問題是,如果我將節點 function 放在 loadAPI 中,我會收到以下錯誤。

Uncaught ReferenceError: require is not defined

有誰知道我如何使用 HTML 中的這個 function?

Uncaught ReferenceError: require is not defined

您收到此錯誤是因為require function 是CommonJS中使用的主要導入 function 。 AWS SDK 不適用於browser-side使用。 在客戶端應用程序上使用它還需要 HTML 文件使用 AWS 憑證並可能將它們暴露在公共 inte.net 上,這可能存在安全風險。

解決將文件上傳到 S3 的要求的更好方法是使用 S3 預簽名 URL。 您可以使用此AWS 指南作為起點,然后查看此博客以了解如何在客戶端應用程序上實施它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM