I'm writing a website using Vue.js that serves as an online store. My client uses Square to manage in-store purchases, so I figured it would be easiest for them if the website gathers certain information from their Square account (like their products, prices, etc.) rather than maintaining a separate copy for the website.
Specifically, I'd like to gather their Square "Catalog" to get the name and price of each item. Per the API examples, I should just be able to make a simple call to catalogApi.listCatalog(), but every time I do this, I get a random axios Network Error:
Error: Network Error
at createError(src\node_modules\axios\lib\core\createError.js:16:15)
at XMLHttpRequest.handleError (http://localhost:5174/node_modules/.vite/deps/square.js?v=82a3bd3e:2474:18)config { url: 'https://connect.squareupsandbox.com/vs/catalog/list' ... }
isAxiosError: true
...
Here is the code that runs the request:
// In vue component..
export default {
async mounted() {
var client = new Client({
accessToken: {MY_ACCESS_TOKEN},
environment: Environment.Sandbox
});
try {
const response = await client.catalogApi.listCatalog();
console.log(response.result);
}
catch (e) {
console.log(e);
}
}
}
The error happens immediately upon calling listCatalog(). I am using the Square Sandbox for testing this. I have ensured that I'm using the correct access token. Additionally, I'm positive that my sandbox contains items in its catalog.
I've read about other developers running into CORS issues with this, but they usually get a specific CORS error, as opposed to the more elusive "Network Error".
When I visit the url in the config section of the request, chrome displays the exact JSON I'm looking for, with no issue.
If someone could help me out with this, I would really appreciate it.
I found out what was going on:
The Square APIs are designed to be hit from backend code (i.e. the server), and not from front end code (i.e. Vue components). To solve the issue, I had to add a simple Express js backend to my app.
I followed a tutorial I found on Code Miner to add the backend to my app. After that, I moved the code above from the
mounted()method to an express router like so:That allowed me to successfully get my catalog info using the Square API.