简体   繁体   中英

Angular, Express & http-proxy-middleware. How to reach remote server?

I'm building MEAN stack app, so I have at backend node+express server, Angular on front.

Atm I need to reach a remote non-cors server with data by sending a POST request to it. Googled for a day, and understand that I need to establish a proxy middleware. Trying to use this on backend server:

app.use(
  "/getPrice",
createProxyMiddleware({
    target: someurl,
    changeOrigin: true,
    logLevel: "debug",
    onProxyReq(proxyReq, req, res) {
      proxyReq.setHeader("X-DV-Auth-Token", sometoken);
      proxyReq.setHeader("Access-Control-Allow-Origin", "*");
      proxyReq.setHeader("Content-Type", "application/json");
      req.body = JSON.stringify(req.body);
    },
  })
);

But request didn't return anything. On other hand trying same url, payload and headers from PostMan, I have response with data exactly I need.

But PostMan offers only request-based solution which I can't adopt for using with express and http-proxy middleware

var request = require('request');
var options = {
  'method': 'POST',
  'url': someurl,
  'headers': {
    'X-DV-Auth-Token': sometoken,
    'Content-Type': 'application/json',
    'Cookie': somecookie
  },
  body: JSON.stringify({requestBodyObject})

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});

Please, point me, where I probably missing a bit, or suggest how to adopt PostMan's code into express & http-proxy solution.

Thanks in advance

Appending req.body in http-proxy should be done using proxyReq.write(JSON.stringify(body)) .

So the modified createProxyMiddleware function would be:


    app.use(
      "/getPrice",
       createProxyMiddleware({
          target: someurl,
          changeOrigin: true,
          logLevel: "debug",
          onProxyReq(proxyReq, req, res) {
            proxyReq.setHeader("X-DV-Auth-Token", sometoken);
            proxyReq.setHeader("Access-Control-Allow-Origin", "*");
            proxyReq.setHeader("Content-Type", "application/json");
            console.log(req.body);
            if (req.body) {
              let bodyData = JSON.stringify(req.body);
              // stream the content
              proxyReq.write(bodyData);
           }
        },
      })
    );

Also, before you try the above changes, please make sure if you are receiving data in req.body or not.

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