How do I get JSON response from a route? - javascript

I have the following route:
#api_blueprint.route("/cars", methods=["GET"])
#jwt_required()
def get_inventory():
with session_scope():
cars = dbu.list_cars()
return jsonify(CarDetails(many=True).dump(cars))
I have to get the JSON response in a GET method which is a list of cars and insert into my html page.
I'm also not sure whether the code after the comment is true, it was one of my attempts to do something.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
/*get here JSON response from a route somehow*/
document.getElementsByClassName("car_name").innerHTML = info.info[1]
document.getElementsByClassName("car_price").innerHTML = info.info[2]
}
else if (xhr.readyState === 4 && xhr.status !== 200){
alert(JSON.parse(xhr.responseText).message);
window.location.reload();
}
};
xhr.send(null);
}
The response is following:
[
{
"carId": 1,
"name": "Chevrolet",
"price": 3547.14
},
{
"carId": 2,
"name": "Lotus",
"price": 4558.47
},
{
"carId": 3,
"name": "Chevrolet",
"price": 4385.96
}
]

When using XMLHttpRequest the response body can be found in the responseText property of the XMLHttpRequest instance. You've misplaced the position of where you read the response.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
// getElementsByClassName returns an array of elements.
// querySelector returns a single element based on a CSS selector.
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
} else {
// statusText shows the status message of the request.
alert(xhr.statusText);
window.location.reload();
}
}
};
xhr.send(null);
Sidenote. Nowadays we have the Fetch API, which is the modern equivalent of the XMLHttpRequest interface. Though it is useful to know how XMLHttpRequest works, I'd recommend learning fetch as well.
The example below is the fetch equivalent of the code above.
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
fetch(url, {
method,
headers: {
"Content-Type": "application/json"
}
}).then(response => {
if (!response.ok) {
throw new Error(`Fetching JSON went wrong - ${response.statusText}`);
}
return response.json();
}).then(data => {
console.log(data);
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
}).catch(error => {
alert(error);
window.location.reload();
});

Related

How to send an Json in GET method in JavaScript?

Hi I'm trying to translate a code in python to Javasrcipt.
import requests
url = "myApi"
r = requests.get(url, json = {"from": "default", "to": "default"})
dic = r.json()
I don't know how to do it in Javascript. Please help me!!!!
Try this:
const url = "myApi";
fetch(`${url}?${new URLSearchParams({
from: "default",
to: "default",
})}`)
.then(res => res.json())
.then(result => console.log('myApi response', result))
you can use XMLHttpRequest :
let xhr = new XMLHttpRequest();
let url = "url?data=" + encodeURIComponent(JSON.stringify({"from": "default", "to": "default"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.from + ", " + json.to);
}
};
xhr.send();

get Id from online hosted Json

I'm trying to get back my jason data that i saved online with the ID that the hosting service set up for me..
const app = new Vue({
el:'#app',
data:{
input:'',
method:'',
status:'200',
timeStart:0,
timeEnd:0,
},
mounted(){
},
methods:{
http_request(){
const url = 'https://' + this.input;
const currentDate = new Date();
this.timeStart = currentDate.getTime();
axios.get(url)
.then(res => {
let parser = document.createElement('a');
parser.href = url;
const protocol = parser.protocol;
const hostname = parser.hostname; // => "example.com"
const pathname = parser.pathname; // => "/pathname/"
const status = res.status;
const method = this.method;
console.log(status, method);
var resp = {
"status": status,
"errors": {},
"data": {
"method": method,
"protocol": protocol,
"hostname": hostname,
"pathname": pathname,
}
}
var response = JSON.stringify(resp);
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("POST", "https://api.jsonbin.io/v3/b", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);
const currentDate = new Date();
this.timeEnd = currentDate.getTime();
console.log((this.timeEnd-this.timeStart)/1000);
console.log(resp)
I'm able to save the json so far on https://jsonbin.io/... and it looks like this:
BIN ID: 6069e05f8be464182c5881f0
{
"status": 200,
"errors": {},
"data": {
"method": "get",
"protocol": "https:",
"hostname": "my-json-server.typicode.com",
"pathname": "/lalith1403/jsonemaillist/list"
}
}
the BIN ID is the unique ID that I need in order to show only the desired jason data.. I saw it in the response metadata but I cannot fina a way to get it..
this is the response after the json is saved:
{"record":{"status":200,"errors":{},"data":{"method":"","protocol":"https:","hostname":"my-json-server.typicode.com","pathname":"/lalith1403/jsonemaillist/list"}},"metadata":{"id":"6069e6a07d0d5e1833cee3f9","createdAt":"2021-04-04T16:17:36.929Z","private":true}}
My idea is then to make a new call with the Id attached to the url in order to get the unique data but I could be wrong..
Thx for your support
Based off their documentation, you'd definitely be able to do this! As part of the URL for the read request, you just need to do a GET request on the following URL: https://api.jsonbin.io/v3/b/<BIN_ID>/latest (you may have been missing this "latest" end of the URL, which specifies which version of the BIN_ID you want - the 1st version, 2nd version after it's been updated, 3rd, etc. Latest will just get the most recent one, which I assume is what you want.
That could look something like this:
let id = "assigned id here"
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("GET", "https://api.jsonbin.io/v3/b/" + id + "/latest", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);

How to convert ajax request from jQuery pure js?

I need to convert this jquery ajax to Javascript.
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf("\"title\":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace("\"", "");
response1 = response1.replace("\"", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
I was googling a lot but I don't how can I push my data by this url in pure js.
If someone knows how to do this, please help.
Here is the sample.
const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// create a JSON object
const json = {
"email": "abc#example.com",
};
// open request
xhr.open('POST', '/subscribes/emailSubscribe');
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(JSON.stringify(json));

Recover public address from a typed signature

I am implementing an application, on which it is necessary to confirm your Ethereum wallet. In order to do so, I am currently writing a basic HTML and Javascript Web page.
This is my javascript code.
const msgParams = [
{
type: 'uint',
name: 'Please verify your generated key',
value: ''
}
]
var signeddata = ''
function sanitizeData (data) {
const sanitizedData = {}
for (const key in TYPED_MESSAGE_SCHEMA.properties) {
data[key] && (sanitizedData[key] = data[key])
}
return sanitizedData
}
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://plapla.pla/initializeVerification', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
msgParams[0].value = xhr.response.key;
console.log(msgParams);
}
}
};
console.log('!');
xhr.send(null);
}
function verify() {
let web3 = window.web3;
console.log(web3);
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use the browser's ethereum provider
web3 = new Web3(web3.currentProvider);
console.log(web3);
} else {
console.log('No web3? You should consider trying MetaMask!')
}
//Login tracken
web3.currentProvider.publicConfigStore.on('update', callback => {
console.log(callback);
//Login tracken
});
console.log(web3.eth.accounts);
web3.eth.getCoinbase(function(error, result){
if(!error) {
console.log("params: "+msgParams[0]);
var fromAddress = result;
web3.currentProvider.sendAsync({
method: 'eth_signTypedData',
params: [msgParams, fromAddress],
from: fromAddress,
}, function (err, result) {
if (err) return console.error(err);
if (result.error) {
return console.error(result.error.message)
}
var sign = {};
sign.data =[{
type:msgParams[0].type,
name:msgParams[0].name,
value:msgParams[0].value
}];
sign.sig = result.result
var json = JSON.stringify(sign);
console.log("Do JSON"+json);
var xhr = new XMLHttpRequest();
console.log("Fa: "+fromAddress);
xhr.open('POST', 'https://plapla.pla/addWallet', true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
// If specified, responseType must be empty string or "text"
xhr.responseType = 'text';
xhr.onreadystatechange = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
}
}
};
xhr.send(json);
});
}
});
};
I am retrieving a random number from my backend on load and want the User to sign this Code with Metamask. I then send it again to my firebase backend, which receives the data as well as the signature.
Firebase handles it as Follows:
exports.addWallet = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const signed = req.body;
console.log(signed);
const recovered = sigUtil.recoverTypedSignature(signed);
return recovered;
})
});
As you can see, I am using the eth-sig-util library: https://github.com/MetaMask/eth-sig-util
But I always get this error from firebase:
TypeError: Cannot read property 'EIP712Domain' of undefined
at Object.findTypeDependencies (/user_code/node_modules/eth-sig-util/index.js:97:47)
at Object.encodeType (/user_code/node_modules/eth-sig-util/index.js:76:21)
at Object.hashType (/user_code/node_modules/eth-sig-util/index.js:127:30)
at Object.encodeData (/user_code/node_modules/eth-sig-util/index.js:42:33)
at Object.hashStruct (/user_code/node_modules/eth-sig-util/index.js:116:30)
at Object.sign (/user_code/node_modules/eth-sig-util/index.js:153:21)
at Object.recoverTypedSignature (/user_code/node_modules/eth-sig-util/index.js:235:36)
at cors (/user_code/index.js:29:31)
at cors (/user_code/node_modules/cors/lib/index.js:188:7)
at /user_code/node_modules/cors/lib/index.js:224:17
So I figured out, that the problem is with the library... Do I send the wrong parameters to the function? Is there any other way to recover the public address from the signer?
You need to use object data, can check code here:
https://github.com/MetaMask/eth-sig-util/blob/master/index.js#L234
{
data: '', // the data you signed
sig: '' // the r, s, v concated string
}
Or you can use ethereumjs-util to recover the public key if you know the signed data.

nodejs xhr POST

I am using nodejs and trying to make a POST command to a server. I am also using node-xmlHttpRequest (driverdan's module). I am having issues with the content-type and get the error:
{
"response":{
"errorCode":"UNKNOWN_ERROR","message":"Content type
'text/plain;charset=UTF-8' not supported","detail":"Content type
'text/plain;charset=UTF-8' not supported"
},"version":"1.0"
}
I need the content-type to be JSON, not text. I have tested the code with GET and it works fine.
Here is my code:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var sys = require('util');
var json_text2 = { "username": "admin","password": "-----" };
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
//- var xmlHTTP = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState === 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("POST",apic_url,true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Accept","application/json");
xhr.responseType = 'JSON';
xhr.send(JSON.stringify(json_text2));
app.locals.apic_nd = xhr.responseText;
Any ideas?
Thanks to jfriend00 I got it working (not sure how to upvote his comment. But here is the code I used:
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
var request = require('request');
var options = {
url: 'https://'+apicem_ip+'/api/v1/ticket',
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: '{ "username": "admin", "password": "----"}'
};
function callback(error, response, body) {
console.log("callback function");
if (!error) {
var info = (JSON.parse(body));
console.log(info);
console.log("status 200");
}
else {
console.log(JSON.parse(body));
}
}
request.post(options, callback);

Categories

Resources