get Id from online hosted Json - javascript

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);

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();

How do I get JSON response from a route?

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();
});

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));

Postman post request works but ajax post does not. Have checked client side js over and over

first question ever on stackoverflow and boy do I need an answer. My problem is that I have an endpoint to create an item, and it works when I send a POST request with Postman. I'm using node and express:
router.post("/", jwtAuth, (req, res) => {
console.log(req.body);
const requiredFields = ["date", "time", "task", "notes"];
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`;
console.error(message);
return res.status(400).send(message);
}
});
Task.create({
userId: req.user.id,
date: req.body.date,
time: req.body.time,
task: req.body.task,
notes: req.body.notes
})
.then(task => res.status(201).json(task.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ message: "Internal server error" });
});
});
That endpoint works when I send with Postman and the req body logged with the right values.
But when I send my ajax request, my server code logs the req.body as an empty object ('{}'). Because Postman works I believe the problem is with my client side javascript but I just cannot find the problem. I and others have looked over it a million times but just can't find the problem. Here is my client side javascript:
//User submits a new task after timer has run
function handleTaskSubmit() {
$(".submit-task").click(event => {
console.log("test");
const date = $(".new-task-date").text();
const taskTime = $(".new-task-time").text();
const task = $(".popup-title").text();
const notes = $("#task-notes").val();
$(".task-notes-form").submit(event => {
event.preventDefault();
postNewTask(date, taskTime, task, notes);
});
});
}
function postNewTask(date, taskTime, task, notes) {
const data = JSON.stringify({
date: date,
time: taskTime,
task: task,
notes: notes
});
//Here I log all the data. The data object and all its key are defined
console.log(data);
console.log(date);
console.log(taskTime);
console.log(task);
console.log(notes);
const token = localStorage.getItem("token");
const settings = {
url: "http://localhost:8080/tasks",
type: "POST",
dataType: "json",
data: data,
contentType: "application/json, charset=utf-8",
headers: {
Authorization: `Bearer ${token}`
},
success: function() {
console.log("Now we are cooking with gas");
},
error: function(err) {
console.log(err);
}
};
$.ajax(settings);
}
handleTaskSubmit();
What I would do:
Change header 'application/json' to 'application/x-www-form-urlencoded' since official docs have no info on former one.
Stop using $.ajax and get comfortable with XHR requests, since jquery from CDN is sometimes a mess when CDN get's laggy and XHR is a native implement and available immediately. Yes it's a code mess, but you always know that it is not the inner library logic thing, but your own problem. You blindly use library, that conceals XHR inside and you do not know how to ask the right question "XHR post method docs" because you are not yet comfortable with basic technology underneath.
Save this and import the variable
var httpClient = {
get: function( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString = '';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
}
if (queryString.length !== 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
}
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.send(null);
},
post: function(url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString='';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
} else {
queryString=data
}
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(queryString);
}
};
usage is as simple as jquery: httpClient.post(Url, data, (xhr) => {})
Check if you have body parser set-up in app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true })); // get information from html forms
if body parser is set-up try changing header to 'multipart/form-data' or
'text/plain'.
For just the sake check req.query
Cheers! :)

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