Posted by & filed under JavaScript, web developing.

Recently I wanted to consume the Google places API and use it in a react view. Immediately I got stuck on the CORS (Cross-Origin Resource Sharing) notification, which made it impossible to use the api.

I tried several solutions, booting chrome with specific security flags, extensions and proxying with browsersync. Nothing worked on my Ubuntu machine.

Solution create your own Node serverside endpoint.

I created a express endpoint which passes the server-side result of the api call to http://locahost:3003/api . You can use it by installing express (express-framework) and calling the script below in node.

const express = require('express');
const fetch = require('node-fetch');

const proxyService = express();
const host = 'localhost';
const port = 3003;

proxyService.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

proxyService.get('/api', function(req, res, next) {
    fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.985103,5.898730&radius=500&types=point_of_interest&key=YOUR_API_KEY`)
        .then(function(res) {
            return res.json();
        }).then(function(json) {
        res.send(json);
    });
});

const server = proxyService.listen(port, function () {
    console.log('API result available at http://%s:%s', host, port);
});

Comments are closed.