Userless Authentication Foursquare API "Missing access credentials" - 400 error - javascript

Bit of a weird one. I'm building a React js app interacting with the Foursquare API, mainly just to learn about React js and APIs.
I'm using Foursquare to get Venue information, that works fine. I also want to use it to get venue photos which is where the fun starts.
The method that processes the original call to venues is as follows. I'm just putting this here for to provide a control as this works fine. It returns the venue information which i process within the app with no problem:
getVenues: (searchTerm) => {
const urlToFetch =
${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602;
return fetch(urlToFetch).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
{
id: item.venue.id,
name: item.venue.name,
// blah
}
));
} else {
return [];
}
})
}
So far, so good, it works fine. However, when I try the same approach accessing the photos endpoint, the method returns a series of objects containing meta which says:
​ code: 400
​​ errorDetail: "Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication for
details."
​​errorType: "invalid_auth"
Suffice to say the information at the link provided doesn't actually give much help :-(
The method I'm using to get the photo information is:
getVenuePhotos: (venueId) => {
const fetchPhotosURL = `${urlPhotos}${venueId}/photos&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
console.log(jsonResponse);
//blah - removed to save space - see method above, it's pretty much the same
})
}
...both are stored in an object in a separate file which the react component imports.
The url vars resolve as follows (asterisks are my addition):
fetchVenuesURL: https://api.foursquare.com/v2/venues/explore?near=london&limit=10&client_id=**** &client_secret=****&v=20180602
fetchPhotosURL: https://api.foursquare.com/v2/venues/4ac518eff964a52064ad20e3/photos&limit=10&client_id=**** &client_secret=****&v=20180602
Does anyone have any idea why this might be happening?
thanks in advance

I think there is a typo in your URL.
Replace
${urlPhotos}${venueId}/photos&limit=10&client...
with
${urlPhotos}${venueId}/photos?limit=10&client...

Related

Algolia + Laravel backend API + nuxtJS

I have a Laravel 8 backend API and a completely separate NuxtJS frontend. I have integrated Algolia into the backend API. I have a nice adapter and service and I can search my index.
Now, I am not interested in using scout because I don't like what it is doing and how it works and that's not the problem so I would like to leave it out of the discussion.
So I've made search work on the frontend with Vuetify autocomplete but I decided to use VueInstant search as this is supposed to save me some work when it comes to integrating query suggestions.
Before I can even get query suggestion I need to get the basic search working with Vue Instant Search.
GOAL
I want to have a VueInstant Search with the backend search client.
WHAT I HAVE SO FAR
THAT IS WITHOUT QUERY SUGGESTIONS JUST THE BASIC SEARCH WITH VUEINSTANT SEARCH
I have backend code that searches my index. I have the frontend code that creates a new connection to my backend (don't worry about how it looks like I just need to get this to work first and then I will invest the time to refactor it):
customSearchClient () {
const that = this
return {
search(requests) {
return that.fetchContainers({ criteria: { query: 'super' }, updateStore: false }).then(response => {
// console.log({ response }, typeof response)
// return response.data.hits
return { results: response.data }
// return response
// return response.data.hits
})
}
}
}
And this is my code for the form:
<ais-instant-search index-name="containers-index" :search-client="customSearchClient()" >
<ais-search-box />
<ais-hits>
<template slot="item" slot-scope="{ item }">
<h1><ais-highlight :hit="item" attribute="name" /></h1>
<p><ais-highlight :hit="item" attribute="description" /></p>
</template>
</ais-hits>
</ais-instant-search>
PROBLEMS
I can get the searchbox to show and query if I remove ais-hits tags. As soon as I add them I get weird errors depending on how I format my response from the backend. I just try to pass it as it is.
I went through some debugging and tried to wrap this into various wrappers as they seem to be missing but eventually it always breaks, for example:
algoliasearch.helper.js?ea40:1334 Uncaught (in promise) TypeError: content.results.slice is not a function at AlgoliaSearchHelper._dispatchAlgoliaResponse (algoliasearch.helper.js?ea40:1334:1)
And that is the Algolia code that breaks.
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results.slice();
states.forEach(function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
SUMAMRY
The ideal solution would be to not to use this InstantSearch thing but I have no clue how to manage more than one index on the server side.
Or am I completely wrong about all of that? Anyone can advise?

Currently learning svelte and need some assistance

Currently I am trying to create a hacker news clone (not from the example given on website). Currently I made an api call that returns an array but I can't seem to get rid of the square brackets. For reference my code is below
onMount(() => {
fetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty&limitToFirst=10&orderBy="$key"')
.then((res) => {
return res.text();
})
.then((text) => {
items = text.split(",");
setTimeout(3000);
data = items.filter((val) => {
return val.replace(/[\[\]']+/g, "");
});
});
//console.log(data);
//getData(items).then(console.log);
});
Thanks in advance!
The API provides a JSON object, but you read it as text (res.text()). Replace this with res.json() and the result will automatically be parsed to an array of IDs.
There is no need to manipulate JSON in string form, just parse it/let it be parsed.

Creating a trello card from the apps script sidebar results in status code 500

I wanted to implement the trello api into a sidebar so my team can create tickets in a more manageable way than texting.
I built the sidebar & functionality using vscode; which is also where I tested everything.
There were no problems until I moved everything to my apps script project; any submission results in Response: 500.
This is the code I wrote to create the card:
function createCard() {
name = document.querySelector('#n').value;
request = document.querySelector('#r').value;
details = document.querySelector('#d').value;
priority = document.querySelector('#high');
idLabels = (priority.checked) ? '62a685a6ea88a630d3da970f' : '62a685b2b835cd665d8ba4ac';
fetch(`https://api.trello.com/1/cards?
key=${key}&
token=${token}&
idList=${idList}&
name=${name} - ${request}&
desc=${details}&
idLabels=${idLabels}`, {
method: 'POST'
}).then(response => {
console.log(`Response: ${response.status} ${response.statusText}`);
return response.text();
}).then(text => console.log(text))
.catch(error => console.error(error));
}
I couldn't find anything that would prevent me from using an api in the sidebar.
This is the closest thing I could find to my current problem is right here:
Google Apps Script to Create Confluence Page -- Results in Status Code 500
but this isn't using sidebar (if that even matters)
Modification points:
When I saw your script, I remembered this issue tracker. In this issue tracker, when // is used in the template literal of the Javascript on HTML service of Google Apps Script as you are using, it seems that // is used as the comment start.
When I saw your following URL, I thought that ${name} - ${request} might be required to do the URL encoding.
`https://api.trello.com/1/cards?
key=${key}&
token=${token}&
idList=${idList}&
name=${name} - ${request}&
desc=${details}&
idLabels=${idLabels}`
When these points are reflected in your script, how about the following modification?
From:
fetch(`https://api.trello.com/1/cards?
key=${key}&
token=${token}&
idList=${idList}&
name=${name} - ${request}&
desc=${details}&
idLabels=${idLabels}`, {
method: 'POST'
}).then(response => {
To:
const encodedName = encodeURIComponent(`${name} - ${request}`);
const url = `https:\/\/api.trello.com\/1\/cards?key=${key}&token=${token}&idList=${idList}&name=${encodedName}&desc=${details}&idLabels=${idLabels}`;
fetch(url, { method: 'POST' }).then(response => {
Note:
When I tested your script, I confirmed the same issue. And, when I tested my proposed modification, I confirmed that the script worked.
When you tested the above-modified script and an error occurs, please check the variables again.
Reference:
When // in template literal is used in an HTML file in the script editor, it is used as a comment start.

How to convert a JS react page into an HTML page

So I'm working on a CMS project that allows users to create their own websites just like wordpress or other CMS platforms...
The users can implement different modals into their websites (text modal, image modal, search modal and other stuff), and then we create an object with the created page infos.
The Object contains all the page infos like the example bellow:
{
pageName: "Home page",
pageLink: "home",
pageSlug: "home-page",
pageMetaDescription: "home meta description",
pageMetaTitle : "home meta title",
pageModals : [
modal1: {
//modal infos here.
}
modal2: {
//modal infos here.
}
]
}
What I'm doing now is stocking these Objects on a database and when the user requests a page, I fetch the object and then generate a react JS file. But this approach isn't the best for performance or SEO.
So I would like to actually generate an HTML file from these Objects and store them in the database and when the user requests a page, it just loads the generated HTML file instead of fetching the Object and populating a react JS page.
If you have an Idea or approach to do this, I would like your help.
Yes you can use Next.js to handle your case
Next allow you to fetch some external data and render html based on api result
Here an example from documentation adapted for your cases
// pagesInfos will be populated at build time by getStaticProps()
function Blog({ pagesInfos }) {
const { pageSlug, pageMetaDescription , pageMetaTitle ...} = pagesInfos
return (
<div>
<h1>{postMetaTitle}</h1>
<p>{pageMetaDescription}</p>
</div>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../getPages')
const pagesInfos = await res.json()
// By returning { props: { pagesInfos } }, the Blog component
// will receive `pagesInfos` as a prop at build time
return {
props: {
pagesInfos,
},
}
}
export default Blog
Here is full docs : https://nextjs.org/docs/basic-features/data-fetching/get-static-props

Retrieve article object including its image using the Shopify JavaScript Buy SDK custom query

I'm using the shopify-buy SDK to try and fetch the articles off of my Shopify store just using JavaScript on the frontend, following the "Expanding the SDK" directions here: https://shopify.github.io/js-buy-sdk/#expanding-the-sdk.
Using the code below, I am able to retrieve my articles and some of the fields that I need.
// Build a custom query using the unoptimized version of the SDK
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data)
})
However, I really need to pull the featured image for each article as well, and unfortunately, when I add the line article.add('image') in my articlesQuery, the resulting articles data logs null. I tried building a custom productsQuery, and that has a similiar problem - I can retrieve some of the product fields, but when I try add the line product.add('images'), I just get null back from the storefront API.
Does anyone have experience building custom/expanded queries and successfully retrieving images?
Try following:
// Fetch all products in your shop
client.graphQLClient.fetchAll().then((acticles) => {
console.log(acticles);
});
And then check in console what sort of available property names your articles have. If SDK allows you get any image data, there should be for sure anything like imageSrc || imageUrl || img......
Thanks to Rebecca Friedman on the js-buy-sdk repo's github issues section for providing this working solution:
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
article.addField('image', {}, (image) => {
image.add('id')
image.add('originalSrc')
})
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data) // works!
})
Because the image field is its own object, you have to add a callback function to specify the fields you need.

Categories

Resources