Search code examples
javascriptpythonnode.jshttpresponsehttp-status-code-403

Response <403> Despite Correct Authorization in nodejs


I am trying to send a post request to a URL, I did this in python with the following code and it worked like a charm and I got a [Response <200>], but since I needed to use this in a website, I switched over to JS and tried to recreate the same functionality, but for some reason I'm getting a [Response <403>] even tho all my auth tokens and headers and everything is same as the python code.

Python Code -

    url = "https://discord.com/api/v8/channels/801784356711956522/messages"
    auth = ""
    headers = {"Authorization": auth,
               'Content-Type': 'application/json', 'referer': "https://discord.com/channels/801784356217421874/801784356711956522"}
    payload = {'content': 'Test' , 'nounce': 802056256326991872, 'tts': False}
    response = requests.post(url, data=json.dumps(payload), headers=headers)
    print(response)

JavaScript Code -

onst url = "https://discord.com/api/v8/channels/801784356711956522/messages"
const auth = ""
const headers = {"Authorization": auth,
                 'Content-Type': 'application/json', 
                 'referer': "https://discord.com/channels/801784356217421874/801784356711956522"}

const options = {
    headers : headers, 
}                

const data = JSON.stringify({'content':"Test" , 'nounce': 802056256326991872, 'tts': false})

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
})

req.on('error', (error) => {
  console.error(error)
})

req.write(data)
req.end()

Solution

  • In your python code, you made a POST request but in JavaScript code, you made a GET request because you did not provide the method option.

    It is specified in https.request options documentation:

    method A string specifying the HTTP request method. Default: 'GET'.

    To make POST request modify like this

    const options = {
        headers : headers,
        method: "POST"
    }                
    

    Also, you need to add URL since you did not provide hostname and path in the options.

    const req = https.request(url, options, (res) => {
      // ...
    })