0
我想要從使用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'標頭。原因'null'因此不允許訪問。'任何想法? – Evan
「Access-Control-Allow-Origin」標頭用於響應(來自服務器),而不是用於請求。有關詳細信息,請參見[Access-Control-Allow-Origin頭文件如何工作?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work)。我不確定問題到底是什麼,但它可能與它們的API有關,因爲它似乎沒有正確處理「OPTIONS」預檢請求。 –