Please see below a minimal example code demonstrating the requested data flow using Multer.
Data flow requested
Request from user ---> Api-Gateway ---> Media service
(form-data + file) (No processing) (Process image/video)
appserver.js
const express = require('express');
const app = express();
app.use(express.static('./'));
app.listen(3000, () => console.log('L@3000'));
apigateway.js
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const app = express();
app.use(cors());
const upload = multer({ storage: multer.memoryStorage() });
app.post('/api/ms', upload.any(), (req, res, next) => {
// forwarding to the media service
fetch('http://localhost:5000/media-service', {
method: 'POST',
body: req.file.buffer,
}).then((response) => {
if (!response.ok) {
next(new Error('Error on forwarding data to the media service'));
}
res.send('sucessfully forwarded to media service');
});
});
app.listen(4000, () => console.log('L@4000'));
mediaservice.js
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const app = express();
app.use(cors());
const upload = multer({ dest: './upload' });
app.post('/media-service', upload.any(), (req, res) => {
res.send('file uploaded successfully');
});
app.listen(5000, () => console.log('L@5000'));
Demonstration
1. Run appserver.js as node appserver.js
2. Run apigateway.js as node apigateway.js
3. Run mediaservice.js as node mediaservice.js
4. Request in Browser as http://localhost:3000
5. It will serve the static file index.html
6. Enter description and select the file to upload
7. Click submit
8. The data will be uploaded to apigateway server first
9. Which then be forwarded to mediaserver
10. In mediaserver, the data will be made permanent
11. A folder upload will store the file
index.html
<!DOCTYPE html>
<html>
<head>
Passing formData to an API gateway
</head>
<body>
<h1>Passing formData to an API gateway</h1>
</body>
<form id="fileinfo" enctype="multipart/form-data">
<label for="description">Description</label>
<input name="description" id="description" />
<br />
<br />
<label for="file">Select file</label>
<input type="file" name="file" id="file" />
<br />
<br />
<input type="submit" />
</form>
<script>
const form = document.querySelector('#fileinfo');
form.addEventListener('submit', async (event) => {
const formData = new FormData(form);
// uploading to the Gateway API
fetch('http://localhost:4000/api/ms', {
method: 'POST',
body: formData,
}).then((response) => {
if (!response.ok) {
throw new Error('Error on uploading file');
}
});
event.preventDefault();
});
</script>
</html>