I am trying to request JSON data from the Genius API from a browser using Webpack and Axios.
This is a Cross-Origin Request, which I know is sometimes tricky. For a while I was getting the following error:
Failed to load https://api.genius.com/songs/378195: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
So I then added Access-Control-Allow-Origin: *
to the headers. Now I get the following error when I try to run npm run build
:
You may need an appropriate loader to handle this file type.
| const headers = {
| Authorization: `Bearer ${ACCESS_TOKEN}`,
| Access-Control-Allow-Origin: *
| };
|
Below is my entry index.js that is being bundled, with my access token removed. I know that webpack 2.x^ loads JSON by default. Any tips on where to go from here?
index.js
const axios = require('axios');
const ACCESS_TOKEN = "XXXXXXXXXXXXXX";
const id = '378195';
const url = `https://api.genius.com/songs/${id}`
const headers = {
Authorization: `Bearer ${ACCESS_TOKEN}`,
"Access-Control-Allow-Origin": "*"
};
window.newSong = function {
axios.get(url, { headers })
.then(response => {
console.log(response.data.response.song);
})
.catch(error => {
console.log(error);
});
}
webpack.config.js
const path = require('path');
const config = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
module.exports = config;