-1

Not a big question but i have to pass file and some data to backend service to handle them via api-gateway.

I Dont want any preprocessing at the api-gateway level all i will do in the backend service only.

Request from user      --->  Api-Gateway     --->  Media service
(form-data + file)         (No processing)          (Process image/video)

I HAVE USED EXPRESS-FILEUPLOAD NPM AND MULTER BUT BOTH NOT WORKING FOR ME ??

app.use('/api/ms', async (req: Request, res: Response, next: NextFunction) => {
    try {
        console.log("--------------------- API Gateway -----------------");
        console.log('Request URL:', req.url);
        console.log('Request Method:', req.method);
        console.log('Request Headers:', req.headers);
        console.log('Request Body:', req.body);
        console.log('Request File:', req.files?.file);



        const response = await axios({
            method: req.method,
            url: 'http://media-service:3001' + req.url,
            data: req.body,
            headers: { 'Content-Type': req.headers['content-type'] } // forward Content-Type
        });

        res.json(response.data);

    } catch (error) {
        console.error('Error in API Gateway:', error);
        res.status(500).json({ error: `Media error - ${error}` });
    }
});
1
  • 1
    "BUT BOTH NOT WORKING", we cannot help without the exact error. Please read how to ask
    – pierpy
    Commented Jul 8 at 16:27

1 Answer 1

0

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.