React配置CORS后,Express后端调用Bing API出现挂起问题求助
Hey there! Let's break down what's going on here and get your app working smoothly. First, a critical clarification: CORS only applies to browser-to-server communication—your Express backend calling the Bing API is a server-to-server request, so CORS rules don't affect that at all. The hang-up you're seeing isn't related to your frontend CORS config; it's almost certainly a problem with how your backend is handling the Bing API call.
Step 1: Optimize Your CORS Configuration (For Security & Reliability)
Your current wildcard (*) setup works, but it's more secure to restrict access to only your React app's origin. Here are two ways to tweak it:
Option 1: Manual Header Setup
Replace your existing CORS middleware with this to allow only http://localhost:3000:
app.use((req, res, next) => { // Restrict access to your React app's origin res.header("Access-Control-Allow-Origin", "http://localhost:3000"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); // Don't forget this! It passes the request to the next middleware/route });
Option 2: Use the cors Package (Easier & More Robust)
Install the official cors package first:
npm install cors
Then configure it in your app.js:
const cors = require('cors'); // Define allowed origin for your React app const corsOptions = { origin: 'http://localhost:3000', optionsSuccessStatus: 200 }; app.use(cors(corsOptions));
Step 2: Fix the Bing API Hang-Up in Your Backend
The hang-up happens because your backend route isn't sending a response back to the frontend—probably because the Bing API call isn't being handled correctly. Here's a proper implementation using async/await (we'll use node-fetch for the API call; install it with npm install node-fetch):
Example /search/results Route Handler
const fetch = require('node-fetch'); const express = require('express'); const router = express.Router(); router.get('/results', async (req, res) => { const searchQuery = req.query.search_query; // Validate input first to avoid unnecessary API calls if (!searchQuery) { return res.status(400).json({ error: 'Search query is required' }); } const bingApiKey = 'YOUR_BING_SUBSCRIPTION_KEY'; // Replace with your actual key const bingApiUrl = `https://api.bing.microsoft.com/v7.0/search?q=${encodeURIComponent(searchQuery)}`; try { // Call Bing API with the mandatory subscription key header const bingResponse = await fetch(bingApiUrl, { method: 'GET', headers: { 'Ocp-Apim-Subscription-Key': bingApiKey // Critical: Bing uses this to authenticate you } }); // Handle non-success responses from Bing if (!bingResponse.ok) { throw new Error(`Bing API request failed: ${bingResponse.statusText}`); } const searchResults = await bingResponse.json(); res.json(searchResults); // Send results back to your React app } catch (error) { console.error('Bing API Error:', error); res.status(500).json({ error: 'Failed to load search results' }); // Send clear error to frontend } }); module.exports = router;
Key Fixes Here:
- Async/Await: Ensures we wait for the Bing API response before sending data back to React—no more hanging requests.
- Mandatory Headers: The
Ocp-Apim-Subscription-Keyheader is required for Bing API access; missing this would cause silent failures or rejected requests. - Error Handling: Catches issues (like invalid API keys or network problems) and sends a clear error response to the frontend instead of leaving it waiting indefinitely.
Quick Recap
- Your CORS config only controls browser access to your Express backend—it doesn't interfere with backend-to-Bing API calls.
- Restricting CORS to your React origin is safer than using a wildcard.
- The hang-up is fixed by ensuring your backend route properly handles the Bing API request, waits for the response, and sends data (or errors) back to React.
内容的提问来源于stack exchange,提问作者A. Cam

