How to get a value from returned JSON in HTML? - html

My client side looks like this:
filename="random_filename.docx"
var response = await fetch("https://backend.wl.r.appspot.com/scriptstuff", {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ file: filename })
});
var data = response.json();
console.log(data);
and my backend return looks like this
response = jsonify({'prediction': str(prob)})
response.headers['Access-Control-Allow-Origin'] = '*'
return response, 200
I receive a promise with the value of 'prediction', but I'm not sure how to access that or why the current code isn't working.
EDIT: adding await before response.json() works

You can execute a function upon a promise being fulfilled by appending a .then() to the fetch request. If you're already receiving the JSON object then the values can be accessed by data.some_key.

I'm not an expert but first store str(prob) into a variable and then create an object with it. I think jsonify() takes things very literally.

Related

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

keeps fetching the old json data?

I'm trying to fetch a json file from a https link however, no matter what link a give the result does not change!?
I validated all the json files. in case they had an error.
the responseData stays the same, and even when I force the data to change by instead returning responseData returning a json manually written; it changes right back to the old json data that just doesnt change when I return responseData back.
And the responseData that I requested to be be posted on the console gives the wrong information
The url given is correct.
but the output doesnt correspond to the data when I fill the link in the internetbrowser.
constructor(props){
super(props);
this.state = {
connected: false,
}
this.init = this.init.bind(this);
this.getJson = this.getJson.bind(this);
this.updateVisited = this.updateVisited.bind(this);
}
init = async ({json})=>{
if(json==null){
await AsyncStorage.setItem('database', "");
alert('error occured');
} else {
await AsyncStorage.setItem('database', JSON.stringify(json));
this.setState({
connected: true
});
}
}
getJson = async ()=>{
var url = await AsyncStorage.getItem("database_url");
console.log(url);
return fetch(url,
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
this.updateVisited(url);
console.log(responseData);
return responseData;
})
.catch(error => {
alert('Could not connect!');
return null;
})
}
connect = async ({url})=>{
await AsyncStorage.setItem("database_url", url);
this.getJson().then(json => this.init({json}));
}
"a_json": [{"name": "greg"}]
"test": [{"name": "sheldon"}]
"temp": [{"name": "bob"}]
when the url points to the json test it gives bob expecting sheldon
when the url points to the json temp it gives bob expecting bob
when the url points to the json a_json it gives bob expecting greg
when returning a json without trying to fetch it from the internet at the place of responseData; it gives the expecting value
If you need more information, feel free to ask.
Thank you for your time reading my question.
The problem was the Cache-Control.
I added 'Cache-Control': 'no-cache' to the header of the fetch, which fixed the problem!
This was pointed out by #Pritish Vaidya in the comments

React-Native Fetch "POST" request throwing "SyntaxError: Unexpected end of JSON input" in Android

this is my function
don't know where is the problem
fetchData() {
fetch(REQUEST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Request : 'menu',
active : '1',
})
}).then((response) => response.json())
.then((responseData) => {
this.setState({
menu: responseData.Response,
});
})
.catch((error) => {
console.warn('error',error);
})
.done();
}
please point out the problem in function
The error occcurs because your response cannot be casted to JSON format. This issue might happen because of wrong header, response body, or other various reasons based on your server. The way to go - since apparently the responses are not consistent - is to perform additional validation of server response before trying to cast the response to JSON.
You can do this by replacing:
.then((response) => response.json())
with
.then((response) => {
// In this case, we check the content-type of the response
if (response.headers.get('content-type').match(/application\/json/)) {
return response.json();
}
return response;
// You can also try "return response.text();"
})
The error will be occcurs because your response can not be casted to be JSON
format.
there are three type of php mysqli api formate
1 formData
2 xml
3 json
i think you are use Formdata api but you are request in json see formdata
example
1) json Request.. example
var Request = {
security:1,
token: token,
email: this.state.username,
password: this.state.password
};
console.log(JSON.stringify(Request));
fetch(API.login, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(Request)
})
.then(res => res.json())
.then(res => {
console.log("Login RESPONCE::: ", res);
}
2)Formdata Example use form data i think your error will be solve
let formdata = new FormData()
formdata.append("Api variable",your post variable)
formdata.append("name",this.state.name)
formdata.append("email, this.state.email)
formdata.append("password",this.state.password)
fetch('http://192.168.1.116/Restaurants/Registration.php', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body:formdata
}).then(res => res.json())
.then(res => {
console.log('Data RESPONCE::', res);
}
then((response) => response.json())
^^^^^^^^^^^^^ I think this is the problem
Responses with status code not equal to 2xx will not go into catch when you use fetch API, therefore you may JSON.parse something such as a HTML page or plain text stream.
You should check if response.ok === true before you parse response as JSON.
The likely cause of this error is your server not returning something that's not valid JSON (likely not JSON at all, like a 404 page or similar).
If you set the request Content-Type to application/json, likely it will send a preflight request to check CORS.
In my React app (not React-Native), I got cross domain issue. My server doesn't support preflight request, and so the response looks like:
{
body: null,
status: 0,
ok: false,
}
which is causing response.json() failed even though I got the expected JSON response in Chrome Dev Tools.
In my case, I change request Content-Type to application/x-www-form-urlencoded which does not require a preflight request. It works as expected.
It might not help in your case but I hope it give you some insight.
Log responseData. It might be possible that API is returning invalid data.

Angular JS issues sending JSON with $ http

I am having issue sending post json data with angular, from PHP I need to access $_POST['action']
This works
$http({
method: 'POST',
url: ajaxurl,
data: "action=get_employer_jobs",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data);
$scope.jobs = data;
});
This does not work
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
console.log('MainController Running');
$http({
method: 'POST',
url: ajaxurl,
data: JSON.stringify({action:"get_employer_jobs"}),
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
console.log(data);
$scope.jobs = data;
});
}]);
You need to process your json on the server side differently.
in PHP, I do it like this:
$_REQUEST = json_decode(file_get_contents("php://input"));
The way Angular sends POST data as json strings, you need to take the whole request string, parse it, then you can use it. It won't automatically be in $_POST or $_REQUEST as a nice array until you do this parsing.
I´d the same problem, it looks like PHP doesn´t fill the $_POST array when it´s passed by the $http service.
Instead of using $_POST, try to parse directly the php://input.
php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
var_dump($request)
Then you can access using the object notation $request->my_var

Reading data from res.end()

I'm sending a simple data back from the server to the client.
app.post('/user', function (req, res) {
var userName = "John";
res.end(JSON.stringify({"error":"", "user": userName}));
});
$.ajax({
type: "POST",
...
contentType : 'application/json',
dataType: "json"
})
.done(function(data) {
// send join message
var resData = JSON.parse(data);
alert("hello"); // this doesn't show up
});
});
});
But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".
If I do JSON.stringify and JSON.parse on the content, it works fine.
alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user);
And also, .done works fine without a data payload from the server i.e. the alert("hello") works.
So, I'm guessing something fishy is happening while sending data within res.end(). Please help.
While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.
The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.