2

What I pretty much want to achieve is add user data, or any data, into my requests to one of my services but like I did in the code below it is not adding to my proxyRequest when sent to my service. Any one know why and how can I achieve that?

app.use('/platform',
  jwtMiddleware,
  (req, res, next) => {console.log(req.user, req.method), next()},
  createProxyMiddleware({
    target: `http://localhost:8000`,
    auth: false,
    changeOrigin: true,
    pathRewrite: {
      [`^/platform`]: '',
    },
    onProxyReq: function onProxyReq(proxyReq, req, res) {
      proxyReq.user = req.user
    }
  })
);

1 Answers1

0

Create a FormData object and add values to it. You will also need to append boundary string to the encoding type header, as well as add a content-length header. The map function will set non-file parameters, and isn't strictly needed.

In the following function I copy existing parameters and add a new one, 'userid'. I also append file data to the request.

function appendFile(proxyReq, req, res) {
    const args = {
        ...req.body,
        userid: "user@id"
    }

    const filepath = Path.join(".", "uploads", req.body.filename);
    const formData = new FormData();

    Object.keys(args).map(key => formData.append(key, args[key]));
    formData.append('fileupload', FS.readFileSync(filepath), 'file.txt');

    proxyReq.setHeader('content-type', `multipart/form-data; boundary=${formData.getBoundary()}`);
    proxyReq.setHeader('content-length', formData.getBuffer().length);

    proxyReq.write(formData.getBuffer().toString("utf-8"));
    proxyReq.end();
}