Cannot load data from Kinvey database - javascript

I have created a database in Kinvey and I am trying to load the data with a onclick event on a button. I tried to console.log my response from the promise to see if I will get the object back, but instead of an object it gives me this error:
error: "The Authorization header in your request is malformed. An Authorization header should contain two parts separated by a space: a type (Basic or Kinvey) and a base64-encoded auth string.
What is wrong with my GET request and why does it return this error, since I already have an Authorization header?
here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Blog</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<h1>All Posts</h1>
<button id="btnLoadPosts" onclick="attachEvents()">Load Posts</button>
<select id="posts"></select>
<button id="btnViewPost">View</button>
<h1 id="post-title">Post Details</h1>
<ul id="post-body"></ul>
<h2>Comments</h2>
<ul id="post-comments"></ul>
<script src="./blog.js"></script>
</body>
</html>
and my JavaScript:
function attachEvents() {
const URL = 'https://baas.kinvey.com/appdata/kid_Sy8W2Z0Y7';
const USERNAME = 'Peter';
const PASSWORD = 'p';
const BASE_64 = btoa(USERNAME + ':' + PASSWORD);
const AUTH = {"Authorization" : 'Basic' + BASE_64};
$('#btnLoadPosts').on('click', loadPosts);
function loadPosts() {
$.ajax({
method: 'GET',
url: URL + 'posts',
headers: AUTH
}).then(function(response) {
cosole.log(response);
}).catch(function(error) {
console.log(error);
})
}
}

Did you forget to add a space after Basic in the authorization header?

Related

how to request API GET with Authentication (login)

I have this html + script code:
<html>
<head>
<title>Curriculum</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
function myFunction() {
url: 'https://www.fulek.com/data/api/supit/curriculum-list/hr',
type: 'GET',
contentType: 'application/json'
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254'
},
success: function (result) {
console.log(result);
},
error: function (error) {
}
}
</script>
</head>
<body>
<td><button type="button" onclick="myFunction()">Delete</button></td>
</body>
</html>
and for some reason the fetch call doesn't work. I got the token when I logged in and got the data from the API:
Here is the error I got for some reason: I have tried a few things but I can't really get it right as I almost dont have experience in JS.
First, I'd recommend learning how promises & async/await work in Javascript before working with APIs.
The problem with your code is two-fold:
You aren't returning anything from the function.
You structured the response as an object. However, the object wasn't placed within curly braces { }.
I fixed the function in the snippet below. Hope this helps:
<html>
<head>
<title>Curriculum</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button type="button" onclick="getData()">Delete</button>
<script src="./testing.js"></script>
<script>
async function getData() {
const response = await fetch("https://www.fulek.com/data/api/supit/curriculum-list/hr", {
method: "GET",
headers: {
"Content-Type": "text/plain;charset=UTF-8",
Authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254",
},
});
const data = response.json()
return data.then(response => console.log(response.data));
}
</script>
</body>
</html>

Dropbox shared_link

I'm writing code to get a link to an image file in Dropbox. However, I get a 400 error.
The error content was "Error in call to API function " sharing / create_shared_link_with_settings \ ": request body: could not decode input as JSON". I think the description method is wrong, but I don't know what's wrong.
<!doctype html>
<html>
<head>
</head>
<body>
<form id="form">
<h3>ファイルを選択してアップロード</h3>
<input type="file" id="file">
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
var input = document.getElementById("file");
//ダイアログでファイルが選択された時
input.addEventListener("change", function (evt) {
//ドロップボックスのファイルAPI
json = {
"url": 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
"raw_url": "https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",
"type": 'post',
"data": {
"{\"path\": \"/hand4.jpg\",\"settings\": {\"audience\": \"public\",\"access\": \"viewer\",\"requested_visibility\": \"public\",\"allow_download\": true}}": ""
},
"headers": {
"Authorization": "Bearer *********",
"Content-Type": "application/json"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.error(data);
}
}
$.ajax(json)
})
</script>
</body>
</html>
The /2/sharing/create_shared_link_with_settings Dropbox API endpoint is an "RPC" style endpoint, meaning it expects its parameters as JSON in the request body.
The error is indicating that you are not sending valid JSON in the request body.
In your code, you're attempting to set that via the data field in your json dict, which is itself a dict with one element, with the key being the escaped string of your desired parameters, and the value being an empty string. That should instead just be the JSON string of the desired parameters.
For example, you probably meant to do something like this instead:
"data": JSON.stringify({"path": "/hand4.jpg","settings": {"audience": "public","access": "viewer","requested_visibility": "public","allow_download": true}}),

Uploading a file with JavaScript/Ajax to SpringBoot endpoint

I am new to front-end development and am having troubles piecing together a solution for this specific form setup.
I have an already created jsp representing this instance creation page. It's a form containing numerous drop downs and check boxes. I need to add a file upload option to it.
The jsp is set up like this...
<form class="form-horizontal" id="editInstanceForm" onsubmit="return false;"> ....
Here's my input field
<div class="form-group" id="uploadForm">
<label class="col-xs-4 control-label instanceDefaultLabel" for="fileSearchField">Default Location and Zoom:</label>
<div class="col-xs-3">
<input name="myFile" type="file" id="fileSearchField" multiple=false>
<button id="upload-button">Upload</button>
</div>
.....
</div>
Now I have an ajax call that I was originally wanting to use before I realized that the whole form is attempting to submit when I uploaded the file. Here it is...
$('#upload-button').click( 'click',
function() {
var form = $('#fileSearchField')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/edit/uploadfile",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert("hi stuff worked");
},
error: function (e) {
alert("nope!");
}
});
}
);
I got this suggestion in researching how to upload a file with jQuery/ajax and Spring Boot (I am using Spring Boot to create my endpoint). Here are some articles that I have been reading in an attempt to understand how to do this...
https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/
http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-ajax-multipartfile-application-downloadupload-files-springboot-jquery-ajax-bootstrap#3_Implement_upload_controller
and many more. This seemed like the solution until I realized this was a form and I think I need to save all the fields at once. This is going to mean that I have to modify the already created ajax function that saves this form and passes it to the end point. Now I don't know how to get my MulitpartFile in as part of this different function. The existing one is like this...
$.ajax({
type: "POST",
url: webroot + "/viewerConfig/mapInstance/insertOrUpdate",
data: JSON.stringify(instanceData),
processData: false,
contentType: 'application/json',
success: function (data) {
if (data.status === "OK") {
alert("Instance created/updated successfully");
} else {
alert("Unknown error");
}
},
fail: function () {
alert("Unknown error");
},
error: function (a) {
alert("Unknown error");
}
});
});
This is exactly where I am stuck and I need to be pointed in the correct and productive direction.
I don't know if this will help but here's my end point that looks like the one I have to hit with my file param added...
#RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody BaseStatusResponse insertOrUpdate(final #RequestBody SaveAdminInstanceView newInstance, HttpServletResponse servletResponse,
#RequestParam MultipartFile file)
EDIT:
I have done some curl troubleshooting and it's the MulitpartFile that's failing. I am passing it as suggested yet I am getting this exception:
org.springframework.web.multipart.MultipartException: The current request is not a multipart request</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
You can try below code:
$.ajax({
url: "/edit/uploadfile",
type: 'POST',
data: new FormData($(this)[0]),
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
cache: false,
success: function(res) {
console.log(res);
},
error: function(res) {
console.log('ERR: ' + res);
}
});
And in controller, you needn't declare consumes = "application/json"
I figured out what I was doing wrong. It wants the form element not the file one. FormData needs the Form. Thanks for your help though! :)
There you have 3 diferent ways to do this with spring-boot at 2022 be sure the file size is lower than the server maximun file size.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="http://192.168.12.168:8081/uploadfile" enctype="multipart/form-data">
<input type="file" id="fileinput" name="file" /><br/><br/>
<input type="submit" value="Submit using HTML" />
</form>
<button onclick="submitStyle1()">Submit using FETCH</button>
<button onclick="submitStyle2()">Submit using XHR</button>
</body>
<script>
function submitStyle1(){
const photo = document.getElementById("fileinput").files[0];
const formData = new FormData();
formData.append("file", photo);
fetch('http://192.168.12.168:8081/uploadfile', {method: "POST", body: formData});
}
function submitStyle2(){
const photo = document.getElementById("fileinput").files[0]; // file from input
const req = new XMLHttpRequest();
const formData = new FormData();
formData.append("file", photo);
req.open("POST", 'http://192.168.12.168:8081/uploadfile');
req.send(formData);
}
</script>
</html>
To see an example type me at https://github.com/JmJDrWrk

How do I use my spotify api token?

So I'm trying to build a random playlist generator using the Spotify API and as I get the info from their server it gives me a 401 code. I followed a tutorial on how to get the access token and now I have it.
My question is how do I use this token now? I've gotten the 401 error again but I think it's because I don't know how to order the url?
JS/html:
const app = {};
app.apiUrl = 'https://api.spotify.com/v1';
var accessToken = '[private_info]';
//Allow the user to enter some names
app.events = function() {
$('form').on('submit', function(e) {
e.preventDefault();
let artists = $('input[type=search]').val();
artists = artists.split(',');
let search = artists.map(artistName => app.searchArtist(artistName));
console.log(search);
});
};
//Go to spotify and get the artists
app.searchArtist = (artistName) => $.ajax({
url: `${app.apiUrl}/search/` + accessToken,
method: 'GET',
dataType: 'json',
data: {
q: artistName,
type: 'artist'
}
});
//With the ids we want to get albums
//Then get tracks
//Then build playlist
app.init = function() {
app.events();
};
$(app.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify Playlist Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="main-container">
<section>
<div class="form">
<img src="images/note.svg" alt="">
<form action="">
<input type="search" value="">
<input type="submit" value="Create">
</form>
<p>Icon created by unlimicon from the Noun Project</p>
</div>
<div class="playlist">
<div class="loader">
<div class="inner-circle"></div>
</div>
</div>
</section>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
I'm still a bit of a newbie at js/ajax (this is my first API project) and I've been following a tutorial where at the time they didn't have to deal with the authorization. Any help or resources appreciated. Thanks.
The access token must be sent in the headers:
curl -X GET "https://api.spotify.com/v1/search?q=Muse&type=track,artist&market=US" -H "Accept: application/json" -H "Authorization: Bearer myToken"
app.apiUrl = 'https://api.spotify.com/v1';
var accessToken = '[private_info]';
//Go to spotify and get the artists
app.searchArtist = (artistName) => $.ajax({
url: `${app.apiUrl}/search`,
headers: {
'Authorization':'Bearer ' + accessToken
},
method: 'GET',
dataType: 'json',
data: {
q: artistName,
type: 'artist'
}
});

Gmail contacts api access error

I want access client gmail contacts using gmail api. but it give error like "Uncaught SecurityError: Blocked a frame with origin "http://" from accessing a frame with origin "https://accounts.google.com". The frame requesting access has a protocol of http", the frame being accessed .
my code
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="jquery-2.1.1.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
dataType: 'jsonp',
data: token
}).done(function(data) {
console.log(JSON.stringify(data));
});
}
</script>
</head>
<body>
<button onclick="auth();">GET CONTACTS FEED</button>
</body>

Categories

Resources