新手求助:从Bitbns获取JSON数据遇CORS跨域错误
Hey there! As someone who stumbled through CORS headaches early in my JS learning journey, I totally get how frustrating this is. Let’s break down what’s going on and how you can fix it:
Why This Error Happens
The message (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://www.bitbns.com’) tells us the bitbns server is set up to only accept requests coming directly from their official website. Since your frontend is running on a different origin (like localhost during development, or your own domain), the browser blocks the request to protect users from malicious cross-site activity.
Solutions to Try
1. Use a Backend Proxy (Best for Production)
Browsers enforce CORS rules, but backend servers don’t. You can build a simple proxy server to act as a middleman: your frontend sends a request to your proxy, the proxy fetches data from bitbns, then passes it back to your frontend.
Here’s a quick example using Node.js and Express:
const express = require('express'); const axios = require('axios'); const app = express(); const PORT = 3001; // Proxy endpoint to fetch bitbns data app.get('/bitbns-data', async (req, res) => { try { // Replace with the actual bitbns API endpoint you're targeting const bitbnsResponse = await axios.get('https://api.bitbns.com/your-target-endpoint'); res.json(bitbnsResponse.data); } catch (error) { res.status(error.response?.status || 500).json(error.response?.data || 'Error fetching data'); } }); app.listen(PORT, () => { console.log(`Proxy server running at http://localhost:${PORT}`); });
Then in your frontend, request http://localhost:3001/bitbns-data instead of the direct bitbns URL.
2. Double-Check Your Origin (If You’re Building for bitbns’ Domain)
If you’re creating a tool that runs directly on https://www.bitbns.com (like a userscript or embedded widget), make sure your frontend’s origin exactly matches the allowed one. Even small differences—like missing www, using http instead of https, or a trailing slash—will trigger this error.
3. Look for Official API Documentation
You might be using an undocumented internal endpoint that’s not meant for external use. Check if bitbns has an official public API—they might have CORS-enabled endpoints or require an API key that lifts this restriction.
4. Temporary Bypass for Local Development
For testing purposes only, you can use a browser extension like Allow CORS: Access-Control-Allow-Origin to disable CORS checks temporarily. This is great for debugging, but don’t rely on it for production—your end users won’t have this extension enabled.
Hope one of these fixes gets you up and running! Let me know if you need help with any of the steps.
内容的提问来源于stack exchange,提问作者Nitin Jindal

