JoseAPL JoseAPL - 10 days ago 4
Javascript Question

express + cors() is not working properly

I'm building a React application and I'm trying to make a call to https://itunes.apple.com/search?term=jack+johnson

I have a helper called requestHelper.js which looks like :

import 'whatwg-fetch';

function parseJSON(response) {
return response.json();
}

function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}

const error = new Error(response.statusText);
error.response = response;
throw error;
}

export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}


So I get:


XMLHttpRequest cannot load
https://itunes.apple.com/search?term=jack%20johnson. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.


My express server looks like this:

const ip = require('ip');
const cors = require('cors');
const path = require('path');
const express = require('express');
const port = process.env.PORT || 3000;
const resolve = require('path').resolve;
const app = express();

app.use(cors());
app.use('/', express.static(resolve(process.cwd(), 'dist')));

app.get('*', function(req, res) {
res.sendFile(path.resolve(resolve(process.cwd(), 'dist'), 'index.html'))
});

// Start app
app.listen(port, (err) => {
if (err) {
console.error(err.message);
return false;
}

const divider = '\n-----------------------------------';
console.log('Server started ✓');
console.log(`Access URLs:${divider}\n
Localhost: http://localhost:${port}
LAN: http://${ip.address()}:${port}
${divider}
`);
});


I have tried using
mode: 'no-cors'
but is not actually what I need since the response is empty.

Am I doing something wrong with this configuration?

Answer

The same origin policy kicks in when code hosted on A makes a request to B.

In this case A is your Express app and B is iTunes.

CORS is used to allow B to grant permission to the code on A to read the response.

You are setting up CORS on A. This does nothing useful since your site cannot grant your client side code permission to read data from a different site.

You need to set it up on B. Since you (presumably) do not work for Apple, you can't do this. Only Apple can grant your client side code permission to read data from its servers.

Read the data with server side code instead.

Comments