WebpackとAxiosを使用しているブラウザからGenius APIからJSONデータをリクエストしようとしています。JSONデータのAPIへのクロス・ソース要求 - 「このファイル・タイプを処理するには適切なローダーが必要です。」
これはクロスオリジンのリクエストですが、時には面倒です。私は次のエラーを得ていたしばらくの間:
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.
だから私は、その後のヘッダーにAccess-Control-Allow-Origin: *
を追加しました。私はnpm run build
を実行しようとする今、私は次のエラーを取得する:
You may need an appropriate loader to handle this file type.
| const headers = {
| Authorization: `Bearer ${ACCESS_TOKEN}`,
| Access-Control-Allow-Origin: *
| };
|
は私のアクセストークンを削除して、バンドルされているというのが私のエントリindex.jsです。私はwebpack 2.xがデフォルトでJSONを読み込むことを知っています。ここからどこへ行くべきかについてのヒント?
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;
ありがとうございます。しかし、私は上記の変更を加えました。私は元の質問に最初のエラーを表示しています。 - 'No 'Access-Control-Allow-Origin'ヘッダーが要求されたリソースにあります。 Origin 'null'はアクセスが許可されていません。 – Evan
'Access-Control-Allow-Origin'ヘッダは、リクエストではなく(サーバからの)応答用です。詳細については、「Access-Control-Allow-Originヘッダーの仕組みは?」(https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work)を参照してください。私は正確に何が問題なのか分かりませんが、OPTIONSのプリフライトリクエストを適切に処理していないようであるため、APIに関連している可能性があります。 –