i have another novice (and probably stupid) question. i am using HttpClientRequest and making a post call. also i have the response.
var url = <my url>
var request = new HttpClientRequest(url);
request.header["Content-Type"] = "application/x-www-form-urlencoded";
request.method = "POST";
try
{
request.execute();
var rawResponse = request.response.body.toString();
}
the response from server is in the following format:
{"token":"abc","expires_in":9292,"refresh":"deeDfTTgendj"}
i just need to extract "expires_in" and "refresh" fields from the response
Since that is valid JSON, you can parse it:
var rawResponse = request.response.body.toString(),
objectLiteral = JSON.parse(rawResponse);
var expires_in = objectLiteral['expires_in'],
refresh = objectLiteral['refresh'];
var rawResponse = '{"token":"abc","expires_in":9292,"refresh":"deeDfTTgendj"}';
objectLiteral = JSON.parse(rawResponse);
var expires_in = objectLiteral['expires_in'],
refresh = objectLiteral['refresh'];
console.log(expires_in, refresh);
Note: check out browser support for JSON.parse()
Related
I'm trying to send a POST request to my .NET API. The values that I need to send are NumeroCupon as an int, NumeroReserva as an int and CapthcaToken as a string. The values for NumeroCupon and NumeroReserva are taken from the url query strings. So, I do the following:
`
let urlParams = new URLSearchParams(window.location.search);
const numCupon = urlParams.get('numerocupon');
const numReserva = urlParams.get('numeroreserva');
const captchaToken = getCookie('captchaToken');
const requestParams = {
NumeroCupon: parseInt(numCupon),
NumeroReserva: parseInt(numReserva),
CaptchaToken: captchaToken
}
axios.post(cuponDataURL, JSON.stringify(requestParams), { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } });
Where requestParams is the body of the post request.
Now, for the API to read the body values correctly, it needs to recieve the correct data types, this means that my back-end is only reading the captchaToken but the expected int values is just reading them as 0s.
What makes me think that is sending the wrong data types? Because if I create a new string, parse it to int and send it, it does work.
Also, if I change my back-end and I select that I want to recieve strings instead of ints it actually reades the values.
So basically this works if I configure the back-end to work with strings:
let urlParams = new URLSearchParams(window.location.search);
const numCupon = urlParams.get('numerocupon');
const numReserva = urlParams.get('numeroreserva');
const captchaToken = getCookie('captchaToken');
const requestParams = {
NumeroCupon: numCupon,
NumeroReserva: numReserva,
CaptchaToken: captchaToken
}
And this also works if my back-end is configured to work with ints (as intended):
let urlParams = new URLSearchParams(window.location.search);
const numCupon = urlParams.get('numerocupon');
const numReserva = urlParams.get('numeroreserva');
const captchaToken = getCookie('captchaToken');
const requestParams = {
NumeroCupon: 117,
NumeroReserva: 343,
CaptchaToken: captchaToken
}
So my question reduces to, how can I send my query string values as an int with axios?
Having a local database running via python, I'm trying to do some api requests to it via a website. First tried both GET's and POST's as python unittest, which worked fine.
Then using javascript; GET function working perfect but my POST function, whatever I do, sends over an empty body to the python function (variable data in python code) or in other words a dict with nothing in it, while I'm passing data through it.
relevant python snippet:
conn = sq3.connect("temp.db", check_same_thread=False)
class Login(Resource):
def post(self):
data = flask.request.form.to_dict()
lst = conn.execute(f"""SELECT AccountID, Role FROM Account
WHERE Email = \"{data['email']}\"
AND PassW = \"{data['passw_hashed']}\"
""").fetchall()
return {"LoginSucces": [{"AccountId": e[0], "Role": e[1]} for e in lst]}
app = flask.Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": '*'}})
api = Api(app)
api.add_resource(Login, "/login")
app.run(port=8080)
Javascript:
function req_login(){
let email_p = document.getElementById("login_email").value
let passw = document.getElementById("login_passw").value
let data = JSON.stringify({email: email_p,passw_hashed: passw.hashCode()});
const request = new XMLHttpRequest();
request.open("POST", IP+"/login");
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader('Content-Type', 'application/json');
request.send(data);
request.onload = (e) => {
let jsret = JSON.parse(request.response);
let topkey = Object.keys(jsret);
let data_arr = jsret[topkey];
alert(data_arr['AccountId']);
}
}
Tried with manual data in javascript as well to see if reading out the data was the problem, without succes with the following bit of code:
const data = `{email: "tst#gmail.com", passw: "testtest123"}`;
Where does it go wrong, what can I try/change. If you need any more info, send in comment
After quite a bit of debugging, I found the solution myself. Hope it helps someone:
replace data = flask.request.get_json()
with data = flask.request.json
i am trying to send a XMLHttpRequest() post request to the Django Server but it shows 403 Forbidden,
after searching i found that it is due to CSRF verification , after seeing lot of similar content still i am unable to figure out how to implement csrf in XMLHttpRequest
i am including the js snippet that i am using
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('click',event => {
if (event.target.id === "add-cart-button")
{ event.preventDefault();
const add_cart_button_id = event.target.dataset.pid
const item_class = event.target.dataset.type
const item_name = event.target.dataset.item
const size_chooser = `#${item_class}-size-${add_cart_button_id}`
var sel = document.querySelector(size_chooser)
const size = sel.value
const quantity_chooser = `#${item_class}-quantity-${add_cart_button_id}`
const quantity = document.querySelector(quantity_chooser).value
var request = new XMLHttpRequest()
request.open('POST','/addcart')
request.onload = () => {
const data = request.responseText
}
var data = new FormData()
data.append('iten_class',item_class)
data.append('item_name',item_name)
data.append('size',size)
data.append('quantity',quantity)
request.send(data)
}
})
})
i am sending this request to /addcart route of django server
def addcart(request):
return JsonResponse({'status':True})
which just returns this status
can anyone help me in csrf verification
I'm using Node's request module.
The response I get is "gziped" or otherwise encoded.
How can I
1. Build the request to not encode the response?
2. Decode the response?
The data is coming from http://api.stackexchange.com.
var myRequest = require('request');
var zlib = require('zlib');
var stackRequest = require('request');
var apikey = '<MyKey>';
var fromdate = '1359417601';
var tagged = 'node.js';
stackRequest(
{ method: 'GET'
, uri: 'http://api.stackexchange.com/2.1/questions?key=' + apikey +
'&site=stackoverflow&fromdate=' + fromdate + '&order=desc&' +
'sort=activity&tagged=' + tagged + '&filter=default'
}, function(err, response, body) {
console.log(response.body); // How can I decode this?
});
The encoding has nothing to do with request. StackOverflow's API returns GZip encoded data always, as explained in the API documentation. You need to use Node's zlib module to unzip the contents. This is a simple example:
var zlib = require('zlib');
// Other code
, function(err, response, body) {
zlip.gunzip(body, function(err, data){
console.log(data);
});
});
The main downside of this, which is bad, is that this forces the request module to process the entire response content into one Buffer as body. Instead, you should normally use Node's Stream system to send the data from the request directly through the unzipping library, so that you use less memory. You'll still need to join the parts together to parse the JSON, but it is still better.
var zlib = require('zlib');
var request = require('request');
var apikey = '<MyKey>';
var fromdate = '1359417601';
var tagged = 'node.js';
var compressedStream = request('http://api.stackexchange.com/2.1/questions?' +
'key=' + apikey + '&site=stackoverflow&fromdate=' + fromdate +
'&order=desc&sort=activity&tagged=' + tagged + '&filter=default');
var decompressedStream = compressedStream.pipe(zlib.createGunzip());
var chunks = [];
decompressedStream.on('data', function(chunk){
chunks.push(chunk);
});
decompressedStream.on('end', function(){
var body = Buffer.concat(chunks);
var data = JSON.parse(body);
// Do your thing
});
First set accept: identity as a header. If stacked change doesn't send data as regular UTF8, then it's a bug on their end.
Secondly, you want to set the encoding as UTF8 so the response isn't a buffer.
var soapre1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">";
var soapre2 = "<soapenv:Header/><soapenv:Body><glob:EmployeeLeaveRequestByParticipantQuery><EmployeeLeaveRequestSelectionByParticipant><EmployeeLeaveRequestParticipantRoleCode listVersionID=\"?\">2</EmployeeLeaveRequestParticipantRoleCode>";
var soapre3 = "<!--Zero or more repetitions:--> <EmployeeLeaveRequestParticipantWorkAgreementIDInterval><IntervalBoundaryTypeCode>1</IntervalBoundaryTypeCode> <!--Optional:--> <LowerBoundaryWorkAgreementID schemeID=\"?\" schemeAgencyID=\"?\">1009</LowerBoundaryWorkAgreementID></EmployeeLeaveRequestParticipantWorkAgreementIDInterval>";
var soapre4 = " <!--Zero or more repetitions:--> </EmployeeLeaveRequestSelectionByParticipant></glob:EmployeeLeaveRequestByParticipantQuery> </soapenv:Body></soapenv:Envelope>";
var soapRequest = soapre1+soapre2+soapre3+soapre4;
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
var soapxhr = Ti.Network.createHTTPClient();
soapxhr.setRequestHeader('SOAPAction',soapRequest);
soapxhr.open("POST","http://erp.esworkplace.sap.com/sap/bc/srt/pm/sap/ecc_empleavereqparctqr/800/default_profile/2/binding_t_http_a_http_ecc_empleavereqparctqr_default_profile");
soapxhr.setRequestHeader('Authorization', authstr);
soapxhr.setRequestHeader('Content-Type','text/xml','charset=utf-8');
soapxhr.send();
soapxhr.onload = function(e)
{
Ti.API.info('abcd');
//get the xml data and let it roll!
var doc = this.responseXML;
Ti.API.info(doc);
}
soapxhr.onerror = function (e){
alert('Error');
Ti.API.info(e);
}
Unable to load the response Its directly getting error
[INFO] {
source = "[object TiNetworkClient]";
type = error;
}
Any one advice how to fix the issue!
# Thanks in advance
In all browser its saying error! but i found some wsdl and soap request so in order to open the response i need to pass the method name to the http request ! then it working