Request forwarding doesn't work in the Serverlees function

I want to redirect all POST requests to some third-party API. For some reason, it doesn’t work
I see nothing in the logs.

Did anybody face something like that?

Here the code


if (request.method === "POST") {
   console.log('==========Message updated start==========');
   const data = JSON.stringify(request.body.data);

    const options = {
      hostname: 'HOST',
      port: 443,
      path: 'PATH',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Content-Length': data.length,
      },
    };

   const forwardedRequest = https.request(options, (res) => {
      //I DON'T SEE THIS IN LOGS
      console.log(`Forwarded statusCode: ${res.statusCode}`);
      
      let responseData = '';
      
      res.on('data', (chunk) => {
        responseData += chunk;
        console.log(responseData);
      });
      
      res.on('end', () => {
        console.log('Response from forwarded request:', responseData);
      });
    });

    forwardedRequest.on('error', (e) => {
      console.log(e);
    });

    console.log(data);
    forwardedRequest.write(data);
    forwardedRequest.end(() => {
       console.log('req end')
   });

   
   console.log('==========Message updated end==========\n');
 
   return response.status(200).end();
 }

If you simply want to proxy from request from Vercel to other server, I guess you could use rewrites: vercel.com/docs/edge-network/rewrites

But if you wish to do it with code… Out of curiosity, is there a reason why you’re using https.request over fetch? Your above code could be converted as:

const res = await fetch('https://hostname/path', {
  headers: {
    accept: 'application/json',
    'content-length': data.length,
    'content-type': 'application/json'
  },
  method: 'POST'
})
const json = await res.json()
console.log('done')

Have you tried that already?

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.