'If I send a request using https.get, it works, but if I use https.request, I am told the request is bad! Can somone explain why?

Why am I getting status 400 using https.request. if i use https.get I have no issues but I want to also be able to send post requests (without relying on fetch or axios)!

Here is my code

  const options = {
    hostname: 127.0.0.1,
    path: api/hubert,
    method: 'POST',
    port: 3000,
    // headers: {
    //     'Content-Type': 'application/json'
    //  },
  };

const testMethod = (options) => new Promise((resolve, reject) => {
  req = http.request(options, (res) => {
    const chunks = []
    res.on('data', chunk => chunks.push(chunk))
    res.on('error', reject)
    res.on('end', () => {
      const { statusCode, headers } = res;
      const body = chunks.join('')
      console.log("resolving")
      resolve({ statusCode, headers, body })
    })
  })
  console.log("request")
  console.log(req.headers)
  req.end()
})

Driver Code:

testMethod(options).then(response => {
  console.log("response!")
  console.log(response)

which yields:

{ statusCode: 400, headers: { connection: 'close' }, body: '' }

the api is just a basic nextjs api (see below) located api/hubert.js content is garbage I only want it to recognize my post request and console log john doe - then I know I am constructing my request properly in Node.

export default function handler(req, res) {
    if (req.method === 'POST') {
        console.log(req)
        res.status(200).json({ name: 'John Doe' })
    } else {
        console.log(req);
        res.status(200).json({error: 'Method not allowed' })
    }
  }


Solution 1:[1]

I needed a forward slash before the path

  const options = {
    hostname: 127.0.0.1,
    path: '/api/hubert',
    method: 'POST',
    port: 3000,
    // headers: {
    //     'Content-Type': 'application/json'
    //  },
  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1