简体   繁体   中英

How to call a NodeJS function from HTML?

I'm trying to create a function that adds a new file into an S3 bucket in AWS. The function works in 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);
  }
});

What I'm trying to do now is take this code and make it execute when a file is uploaded in HTML. I have a simple HTML script where users can upload files and I want the above code to execute when the submit button is pressed.

<!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>

The problem is that if I put the node function within loadAPI, I get the following error.

Uncaught ReferenceError: require is not defined

Does anyone know how I can utilize this function from HTML?

Uncaught ReferenceError: require is not defined

You are getting this error because require function is the primary importing function used in CommonJS . AWS SDK is not meant for browser-side usage. Using it on client-application will also require the HTML file to use AWS credentials and potentially expose them over the public inte.net which could be a security risk.

A better way of tackling your requirement of uploading files to S3 is the use of S3 pre-signed URLs. You can use this AWS guide as a starting point and then check out this blog after to get an idea on how to implement it on client-side apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM