Shopify基于Node.js+React开发的App中,前端ScriptTag向后端传输数据的实现疑问
Hey there! Let's tackle your two questions step by step and get that fetch call working for your Shopify app.
1. What URL should I use for POST/GET requests?
The URL you’ll use points to an API endpoint you build in your Node.js backend specifically for handling wishlist actions. For example, if you set up a route to handle adding items to the wishlist, your URL might look like https://your-app-backend-domain.com/api/wishlist/add.
A couple of important notes:
- Since your ScriptTag runs on the Shopify store’s domain (different from your backend’s domain), you’ll need to configure CORS in your Node.js backend to allow cross-origin requests. Packages like
corsfor Express make this straightforward. - If you’re using Shopify’s App Proxy feature, you could also use that proxy URL (e.g.,
https://your-store.myshopify.com/apps/your-app-slug/wishlist/add), but a direct backend endpoint is simpler for most initial setups.
2. Can the fetch function submit variable values?
Absolutely! You can pass your customer and productid variables directly in the request body. Just make sure to convert them to JSON format (using JSON.stringify()) and set the correct Content-Type header so your backend can parse the data.
Updated ScriptTag.js Code
Here’s how to modify your addWishList function to send the variables to your backend properly:
const header = $('header.site-header').parent(); header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'}) function addWishList(customer, productid){ // Replace this with your actual backend API endpoint const backendUrl = 'https://your-app-backend-domain.com/api/wishlist/add'; fetch(backendUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', // If your backend requires Shopify store authentication, add relevant headers here // For example, if you have the store's access token stored securely: // "X-Shopify-Access-Token": "your-store-access-token", }, body: JSON.stringify({ customerId: customer, productId: productid }) }) .then(response => { if (!response.ok) { throw new Error('Failed to add item to wishlist'); } return response.json(); }) .then(data => { console.log('Successfully added item to wishlist:', data); }) .catch(error => { console.error('Error adding wishlist item:', error); }); } function removeWishList(){ console.log('removing item from the wishlist!!') // Add a similar fetch call here for removing items } var wishbtn = document.querySelector('.wishlist-btn') wishbtn.addEventListener('click', function(){ if(this.classList.contains('active')){ removeWishList(); this.classList.remove('active'); this.innerHTML = 'Add to wishlist' } else{ var customer = wishbtn.dataset.customer; if(customer == null || customer == ''){ console.log('Please log in to add this item to your wishlist') } else{ var productid = wishbtn.dataset.product; this.classList.add('active'); this.innerHTML = 'Remove from wishlist' addWishList(customer, productid); } } })
Quick Backend Setup Example (Node.js/Express)
To receive the data in your backend, you’ll need a route that parses the JSON body and interacts with Firebase. Here’s a simple Express example:
const express = require('express'); const cors = require('cors'); const { initializeApp } = require('firebase/app'); const { getFirestore, collection, addDoc } = require('firebase/firestore'); const app = express(); // Enable CORS (restrict to your store's domain in production) app.use(cors({ origin: '*' })); // Parse JSON request bodies app.use(express.json()); // Initialize Firebase (use your project config) const firebaseConfig = { apiKey: "your-api-key", authDomain: "your-auth-domain", projectId: "your-project-id", // ... other Firebase config fields }; const firebaseApp = initializeApp(firebaseConfig); const db = getFirestore(firebaseApp); // Handle adding wishlist items app.post('/api/wishlist/add', async (req, res) => { try { const { customerId, productId } = req.body; // Save data to Firebase await addDoc(collection(db, 'wishlists'), { customerId, productId, createdAt: new Date() }); res.status(200).json({ message: 'Item added to wishlist!' }); } catch (error) { res.status(500).json({ error: 'Failed to save wishlist item' }); } }); app.listen(3000, () => console.log('Backend server running on port 3000'));
Remember to replace placeholder values (like your backend URL and Firebase config) with your actual project details. In production, make sure to secure your endpoint (e.g., validate Shopify HMAC signatures to ensure requests come from trusted stores).
内容的提问来源于stack exchange,提问作者Huma

