当我尝试与代理服务器通信时遇到 CORS

问题描述 投票:0回答:1

大家好,我需要你的帮助 我想使用 Google Places api 获取用户位置最近的医院,我尝试直接在前端实现它,但我不断收到 CORS 错误,“https://res-q.vercel.app”已被阻止CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

我的一个朋友建议我设置一个简单的代理服务器来消除 CORS 错误。当我设置它并在本地托管它时,它工作正常,我能够使用 Google Places api。但是当我在 vercel 上托管代理服务器后,我再次遇到相同的错误。

总而言之,它可以在本地主机中运行,但当我向 vercel 上的服务器发出请求时,出现 Cors 错误。

这是我尝试运行的前端函数: `

const fetchNearbyHospitals = async () => {
        try {
            const response = await axios.get('https://res-q-google-api-proxy-server.vercel.app/maps/api/place/nearbysearch/json', {
            params: {
                location: `${userLocation.latitude},${userLocation.longitude}`,
                radius: 1500,
                type: 'hospital',
                key: 'the api key was here' 
            }
            
            });

            const hospitalData = response.data.results;
            console.log("Response: ", response)
            console.log("Hospital fetched: ", hospitalData)
            if (hospitalData.length > 0) {
                let closestHospital = hospitalData[0];
                let closestDistance = calculateDistance(userLocation, closestHospital.geometry.location);
                for (let i = 1; i < hospitalData.length; i++) {
                    const hospital = hospitalData[i];
                    const distance = calculateDistance(userLocation, hospital.geometry.location);
                    if (distance < closestDistance) {
                        closestHospital = hospital;
                        closestDistance = distance;
                    }
                }
                setClosestHospital(closestHospital);
                console.log("Closest Hospital: ", closestHospital)
            }
        } catch (error) {
            console.error('Error fetching nearby hospitals:', error);
        }
    };
    

虽然代理服务器代码是

const express = require('express');
const axios = require('axios');
const app = express();


app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});


// Define your route to proxy requests to the Google Maps API
app.get('/maps/api/place/nearbysearch/json', async (req, res) => {
    try {
        const { location, radius, type, key } = req.query;
        const apiUrl = `https://maps.googleapis.com/maps/api/place/nearbysearch/json`;

        const response = await axios.get(apiUrl, {
            params: {
                location,
                radius,
                type,
                key
            }
        });

        // Forward the response from the Google Maps API to the client
        res.json(response.data);
    } catch (error) {
        console.error('Error proxying request:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Start the server
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

node.js express google-maps-api-3 cors
1个回答
0
投票

我认为制作代理服务器来解决这个问题非常好:) 并且您已经添加了此标题

Access-Control-Allow-Origin:*
。这已经足够了,但如果你仍然遇到问题,那么你可以尝试添加这个。

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); //<- already exists
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');

    // Handle preflight requests
    if (req.method === 'OPTIONS') {
        res.sendStatus(204);
    } else {
        next();
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.