JSON data cannot be accessed getting error 404 (TMDB)? - javascript

I want the poster of required movie from TMDB. I am not able to get JSON data from TMDB API. I have send the request but getting error 404 'The resource you requested could not be found'.
Link to access TMDB movie API : https://developers.themoviedb.org/3/movies/get-movie-images
Here is my code:
<script type="text/javascript">
var film = "speed";
var api_key = 'my-api-key';
var requestURL = "https://api.themoviedb.org/3/movie/images?api_key=" + api_key +"&language=en-US&callback=?";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response; //request.response contains all our JSON data
console.log(myjsondata);
}
</script>
The JSON data in my console should look like this:
But instead I am getting this in my console:error 404 This resource cannot be found.

You need to include a movie_id value in the path part of the request URL, right? Like this:
var requestURL = "https://api.themoviedb.org/3/movie/"
+ movie_id + "/images?api_key=" + api_key +"&language=en-US&callback=?";
At least in the documentation cited in the question that’s what’s shown:
GET /movie/{movie_id}/images
Path Parameters
movie_id : integer
Example:
https://api.themoviedb.org/3/movie/{movie_id}/images?api_key=<<api_key>>
For example, to get JSON-formatted data for the images for the movie with the ID 9340:
https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>
You can confirm that works by testing with curl or whatever:
$ curl "https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>"
{
"backdrops": [
{
"aspect_ratio": 1.777251184834123,
"file_path": "/qKeyO9gXaaK0g87tvvqOPK1siwc.jpg",
"height": 1688,
"iso_639_1": null,
"vote_average": 5.454545454545455,
"vote_count": 3,
"width": 3000
},
…

Related

How to call the REST method POST /wallet/{name}/setDefault using Javascript?

I have been working on Hyperledger composer for my project. I am trying to build a multi user web app. But I can't however, call the REST method POST /wallet/{name}/setDefault.
I used the code below to do a POST request but it returns an error "Unhandled error for request POST /api/wallet/admin%40sample/setDefault: Error: Authorization Required"
function myLogin(){
var id = document.getElementById("bId").value;
var signIn = id + "#sample";
var xhr = new XMLHttpRequest();
var url = "http://localhost:3000/api/wallet/" + id + "%40sample/setDefault";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var obj ={
"name": signIn
}
var data = JSON.stringify(obj);
xhr.send(data);
console.log(url);
}
I have used Github oauth and had already given authorization to each and every participant in the network. But still, it shows the Error.

XHR doesnt send json object

I have client - server express app. Im trying to send an XHR request from frontend to my controller, while passing json data. My frontend code looks like this:
function handle_login(){
var username_field = document.getElementById('input_username');
var pass = document.getElementById('input_password');
if(username_field.value!=null)console.log(username_field.value);
console.log(pass.value);
//window.location.href = "/loginAttempt/"+username.value+"-"+pass.value;
var xhr = new XMLHttpRequest();
var url = "/home_pogled";
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/json");
var data = {
username : username_field.value,
password : pass.value
}
var json = JSON.stringify(data);
xhr.send(json);
xhr.onload = function() {//ob uspesnem odgovoru
var responseText = xhr.responseText;
//console.log("Backend server response -" +responseText);
// uporabi odgovor
};
xhr.onerror = function() {
console.log('There was an error!');
};
}
I can send the request and i'm certain that data is written to the json object prior to sending it, but when i do consonle.log(req.body) in my controller upor receiving the request the body is empty "{}", where is should havec ontained the username and password values in a json objkect. What am i missing?
Client Side:
We can't send object in GET method, it should be query params like below snippet
let url = `/home_pogled?username=${username_field.value}&password=${pass.value}`;
xhr.open('GET', url);
Server side (express app):
In express js, we can get the query params in req.query
let username = req.query.username;
let password = req.query.password

why does my javascript code read a property of null on this json data?

EDIT: sorry, had the code ridden with errors. changed it now
Ive been trying to extract some JSON data from a github link to put it in a html file, but everytime I try to do so (with the code below), I get an Uncaught TypeError: cannot read property "value" of null. This even though "value" (in the Json file) certainly is not null.
What is going wrong here?
Thanks
you can check out the json file i put on github https://github.com/BearsAreFriendly/PolitiekeHelderheid/blob/master/kamerleden.json . I am quite certain that "value" has been defined
var section = document.querySelector("section");
var requestURL = 'https://github.com/BearsAreFriendly/PolitiekeHelderheid/blob/master/kamerleden.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var phdata = request.response;
showKamerleden(phdata);
}
function showKamerleden(jsonObj) {
var kamerleden = jsonObj["value"];
for (var i = 0; i < kamerleden.length; i++) {
var myPara1 = document.createElement('p');
myPara1.textContent = kamerleden[i].Id;
section.appendChild(myPara1);
}
}
this should print out the id's. instead I get my mentioned error code
I believe you may not actually be receiving any JSON data from GitHub, but HTML. When my browser requests a GitHub page the response content type is Content-Type: text/html. Your request URL should respond with JSON in order for it to be usable. When you request the GitHub URL you are likely getting other stuff (such as HTML), but not JSON.
For example, this url serves JSON data only: https://my-json-server.typicode.com/typicode/demo/posts
It has Content-Type: application/json when I inspect the page in dev tools under the network section
Modifying your code to add the url below works perfectly.
var section = document.querySelector("section");
var requestURL = 'https://my-json-server.typicode.com/typicode/demo/posts';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var phdata = request.response;
/* showKamerleden(phdata); */
document.write(JSON.stringify(phdata) )
}
try this
var kamerledens = jsonObj.value;
instead of
var kamerledens = jsonObj["value"];
and also you should use a loop to go through all ids
function showKamerleden(jsonObj) {
var kamerledens = jsonObj.value;
for (var i = 0; i < kamerledens.length; i++) {
var myPara1 = document.createElement('p');
myPara1.textContent = kamerledens[i].Id;
section.appendChild(myPara1);
}
}
Edited:
Try moving
request.send();
after the onload function
It isn't "value" that it is null, jsonObj is null.
Hence the error 'cannot read property "value" OF null'
I suggest you output and analyse the request in the callback
console.log(request)

Troubles with Fetch and XMLHttpRequest in javascript

So I'm doing an assignment for school and am having troubles using an API in java script. When I use XMLHttpRequest I receive the status code "0". After being frustrated from trying with XML I tried using fetch, I now get the error "Fetch failed loading: OPTIONS 'https://api-us.faceplusplus.com/facepp/v3/detect'"
To put it in context I have converted an image to base64 and need to parse that base64 as a parameter to face++ in order to do some face recognition stuff, should be cool when it works!
Here is the XML code:
function getInfo(base64) {
var request = new XMLHttpRequest();
request.open("POST", "https://api-us.faceplusplus.com/facepp/v3/detect");
request.setRequestHeader('api_key', 'my key');
request.setRequestHeader('api_secret', 'my secret');
request.setRequestHeader('image_base64', toString(base64));
request.send(null);
request.onload = function() {
console.log(request.status());
}
}
And here is the same thing attempted with fetch:
function getInfo(base64) {
var url = "https://api-us.faceplusplus.com/facepp/v3/detect"
var data = {
"api_key":"my key",
"api_secret":"my secret",
"image_base64":toString(base64)
}
var params = {
headers:{
"Content-Type":"application/json; charset=UTF-8"
},
body:data,
method:"POST"
}
fetch(url, params).then(data=>{return data.json()}).then(res=>{console.log(res.statusText)}).catch(error=>console.log(error))
}
I'm obviously missing something here and would really appreciate any help! Hope I've formatted this correctly.
you could try removing the headers params. This error
Fetch failed loading: OPTIONS
is because you are sending some header that is not recognized by the server, i would start there.

Bad JSON request using One Drive API

My goal is to create a folder programmatically in OneDrive API using Javascript/Jquery in the application that I'm building. I am not using Node.js or Angular.js. I have registered my application with OneDrive's Application Registration Portal, then used the token flow to get the access token from my web browser url address bar. Now that I have the access token, I'm trying to send it and my request to the API. Below is my code:
var accesshash = window.location.hash.substring(1);
//console.log(url);
console.log(accesshash);
var token = JSON.parse('{' + accesshash.replace(/([^=]+)=([^&]+)&?/g, '"$1":"$2",').slice(0,-1) + '}', function(key, value) { return key === "" ? value : decodeURIComponent(value); });
console.log(token.access_token);
var url = "https://graph.microsoft.com/v1.0/me/drive/root/children/"
var xhr = new XMLHttpRequest();
if(xhr.readyState == 4) {
console.log("success");
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);
var newfolder = {
"name": "0000000000",
"folder": {}
}
xhr.send(newfolder);
I'm getting this as my JSON response:
{
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
"request-id": "c8d43cbc-a59b-4244-8c4e-9193295ec7f8",
"date": "2018-06-07T19:42:57"
}
}
}
Does this mean that my access token is at least valid? Or is something wrong with it? Is there something I'm missing? This is my first time attempting to integrate Onedrive API into an application.
You are sending object, but content type is application/json, json is string representation of javascript object
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); // added charset
xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);
var newfolder = {
"name": "0000000000",
"folder": {}
}
xhr.send(JSON.stringify(newfolder)); // converted to string
There are many http libraries like fetch, request - that can make your life much easier

Categories