简体   繁体   中英

Jquery equivalent of Python requests.post()

So i was trying to work with HackerEarth Api and wanted to incorporate the compile/run feature on my website. According to the documentation that can be found here - https://www.hackerearth.com/docs/wiki/developers/v3/ i got to know that using the following python script i can get a json response for my code .

   #! -*- coding: utf-8 -*-

import requests

# constants
RUN_URL = u'https://api.hackerearth.com/v3/code/run/'
CLIENT_SECRET = '5db3f1c12c59caa1002d1cb5757e72c96d969a1a'
#not my own secret key

source = "print 'Hello World'"

data = {
    'client_secret': CLIENT_SECRET,
    'async': 0,
    'source': source,
    'lang': "PYTHON",
    'time_limit': 5,
    'memory_limit': 262144,
}

r = requests.post(RUN_URL, data=data)
print r.json()

I tried running the above code and it works fine. My site is built using plain html,cc,js,jquery,bootstrap and i was trying to get this working using jquery post method .

What i tried was -

code=document.getElementById('codeinput').value;
langaugeUsed=document.getElementById('languageSelector').value;
url='https://api.hackerearth.com/v3/code/compile/';
secret = '5db3f1c12c59caa1002d1cb5757e72c96d969a1a';    //not my own secret key


$.post(url, {client_secret: secret,
async: 0,
source: code,
lang: languageUsed,
dataType:'json',
time_limit: 5,
memory_limit: 262144 },
     function(returnedData){
        alert(returnedData);
}, 'json');

When i checked my console i had these errors after trying to run the script -

Failed to load resource: the server responded with a status of 403 (Forbidden) index.html#:1 XMLHttpRequest cannot load https://api.hackerearth.com/v3/code/compile/ . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

Can anyone help me with this issue?

You are facing the issue due to CORS . By Default, Browser don't allow to send the request on different urls. So you need to manually allow this by adding the CORS header.

You can take a good look at CORS Python Library

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