I'm trying to get JSON product data from Snipcart by querying my Netlify function as below:
const fetch = require("isomorphic-fetch"); const {SNIPCART_PRIVATE_KEY} = process.env; const API_ENDPOINT = "https://app.snipcart.com/api/products"; const SNIPCART_ID = qs.stringify(event.queryStringParameters); const callAPI = async (event, context) => { const auth = 'Basic ' + Buffer.from(SNIPCART_PRIVATE_KEY + ':' + '').toString('base64'); const t = await fetch(API_ENDPOINT + "?userDefinedId=" + SNIPCART_ID, { headers: { Authorization: auth, Accept: 'application/json', }, }) .then(response => response.json()) .then(data => { var results; if (data) { const {items} = data; if (items) { return { name: items[0].name, sales: items[0].statistics.numberOfSales, }; } } return results; }) .catch(error => ({statusCode: 422, body: String(error)})); return { statusCode: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept', }, body: JSON.stringify(t), }; }; exports.handler = callAPI; I get the correct JSON data when I hard-code SNIPCART_ID in the function above. But I can't pass my Snipcart id as a parameter using my page's JavaScript as follows:
document.addEventListener("click", function (event) { if (!event.target.matches("#collapsible")) return; let SNIPCART_ID = 123; let URL = "/.netlify/functions/snipcart-getsales"; fetch(URL, ${SNIPCART_ID}); .then((response) => response.json()) .then((data) => renderSales(data)) .catch(() => renderError()); }); function renderSales(data) { const name = document.getElementById("name"); const sales = document.getElementById("sales"); const error = document.getElementById("error"); error.innerHTML = ""; name.innerHTML = data.name; sales.innerHTML = data.sales; } function renderError() { const error = document.getElementById("error"); error.innerHTML = "Whoops, something went wrong. Please try again later!"; } What am I doing wrong here?
https://stackoverflow.com/questions/67427200/pass-query-parameters-to-snipcart-api-url-inside-a-netlify-function May 07, 2021 at 07:31AM
没有评论:
发表评论