Search code examples
pythonnode.jsreddit

How do I fix this error that I'm getting while making a POST request in nodejs


So, I wrote the following code to post an image on Reddit using Reddit API.

const request = require('request')

let access_token = "redacted"
let url = 'https://oauth.reddit.com/api/submit'

let headers = {
    'Content-type': 'application/x-www-form-urlencoded',
    "Authorization": "bearer " + access_token,
    "User-Agent": "manage your reddit easily in the maxi time created in some idea of mine by u/_jaypatel"
}

let data = {
    'sr':'testingground4bots',
    'api_type': "json",
    'title': 'Testing post creation',
    'spoiler': false,
    'nsfw' : false,
    'resubmit': false,
    'sendreplies': false,
    'text':"This is raw api test",
    'kind':'image',
    'url':'https://i.imgur.com/fLZ35cI.jpg',
    "extension": "json"
}


var options = {
  url, headers, data
}

request.post(options,function (error, response, body) {
        if (error) {
            console.log(error);
        }
        else{
          console.log(body);
        }
    }
);

And I've been getting this error again and again.

{"jquery": [[0, 1, "call", ["body"]], [1, 2, "attr", "find"], [2, 3, "call", [".status"]], [3, 4, "attr", "hide"], [4, 5, "call", []], [5, 6, "attr", "html"], [6, 7, "call", [""]], [7, 8, "attr", "end"], [8, 9, "call", []], [1, 10, "attr", "find"], [10, 11, "call", [".error.BAD_SR_NAME.field-sr"]], [11, 12, "attr", "show"], [12, 13, "call", []], [13, 14, "attr", "text"], [14, 15, "call", ["This community name isn't recognizable. Check the spelling and try again."]], [15, 16, "attr", "end"], [16, 17, "call", []]], "success": false}

I first wrote a Python script as follows and it worked, I want to write one in Node JS but I can't do it. Here is the python code

import requests

access_token = "redacted"

headers = {
    "Authorization": "bearer " + access_token,
    "User-Agent": "manage your reddit easily in the maxi time created in some idea of mine by u/_jaypatel"
}


data = {

    'sr':'testingground4bots',
    'api_type': "json",
    'title': 'Testing post creation',
    'spoiler': False,
    'nsfw' : False,
    'resubmit': False,
    'sendreplies': False,
    'text':"This is raw api test",
    'kind':'image',
    'url':'https://i.imgur.com/fLZ35cI.jpg',
    "extension": "json",
    "uh":"74641dhxxdd1d8da2f8d06d267dec57369ffcb6098cc7cd2f1"
}

r = requests.post("https://oauth.reddit.com/api/submit", headers=headers, data=data)

content = r.json()

print(content)

How do I fix my Node JS script to make it work? Any help would be appreciated.


Solution

  • I found the answer myself. I'm so dumb, ahhhhhh

    Here, change this

    var options = {
      url, headers, data
    }
    

    to this

    var options = {
      url, headers, form:data
    }