How do I use my spotify api token? - javascript

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

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>

CSFR protection how to do it best without Laravel

Info: I don't use Laravel.
In a post on stack I saw how you can protect yourself against CSFR .
Unfortunately, this contribution only related to a Laravel application and I'm not sure whether I can integrate it into my code just like that without using Laravel and if not whether there is another way to elegantly protect myself from CSFR ?
I'm not quite sure if it even makes a different using Laravel or not. Here is my code:
<head>
<title>Newsletter</title>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}"> // copied form the post
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup({ // copied form the post start here
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
}); // copied form the post end here
$("#newsletter-form").submit(function(event) {
event.preventDefault();
var thisemail = $("#newsletter-email").val();
var thisdatenschutz = $("#newsletter-datenschutz").val();
var thissubmit = $("#newsletter-submit").val();
$.ajax({
type: "POST",
url: "submitemail.php",
data: {
email: thisemail,
datenschutz: thisdatenschutz,
submit: thissubmit
},
success: function(data) {
document.getElementById("response").innerHTML = data;
$("#newsletter-email").val("");
$('input[type=checkbox]').prop('checked',false);
}
});
});
});
</script>
</head>

How perform PATCH request from html form using NodeJS?

This was my attempt to perform a patch request on an HTML form from the frontend to MongoDB database via NodeJS API.
This is a Nodejs API structure
app.route("/requests/:rollno")
.get(function(req, res) {
// get method to find a query
})
.patch(function(req, res) {
Request.update({
rollno: req.params.rollno
}, {
$set:req.body
},
function(err) {
if (!err) {
res.send("Successfully updated requests");
}else{
res.send(err);
}
}
);
});
On the frontend side of the form
<%- include('partials/header') %>
<h1>Recent requests</h1>
<% for(let i = 0; i < posts.length; i++) { %>
<article>
<form action="/requests/21" method="PATCH">
<input type="text" name="status[0]">
<div id="participant"></div>
<br>
<button type="button" onclick="addParticipant()">Add</button>
<button type="button" onclick="delParticipant()">Remove</button>
<div class="btn-block">
<button type="submit" href="/success">Submit Request</button>
</div>
</form>
</article>
<% } %>
The form is not actually updating the information on the actual server. But with the postman, the data is getting updated.What's the best resolution for the same or is there any alternate method for the same ?
<form action="/requests/B194057EP" method="PATCH">
This is invalid, HTML forms method attribute only supports GET and POST method. <form method="put"> is invalid HTML and will be treated like a GET request.
Now to solve this, you can make use of Jquery AJAX to send data from the client-side to your backend.
$.ajax({
url: '<api url>',
type: 'PATCH',
data: {
data: sendData
},
success: function () {
}
})
;
In vanilla JS, you can use promises, as well as async/await to do so, this is a basic example of it.
async patching() {
const responseFlow = await fetch(URL, {
method: "PATCH",
headers: {
'Content-Type': 'application/json'
},
// The content to update
body: JSON.stringify({
name: "New name"
})
})
}

Cannot load data from Kinvey database

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?

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