javascript - 对 API 的 JSON 数据的跨源请求 - "You may need an appropriate loader to handle this file type."

标签 javascript json node.js webpack cross-domain

我正在尝试使用 Webpack 和 Axios 从浏览器的 Genius API 请求 JSON 数据。

这是一个跨源请求,我知道这有时很棘手。一段时间我收到以下错误:

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: * 添加到 header 中。现在,当我尝试运行 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,其中删除了我的访问 token 。我知道 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;

最佳答案

您的 headers 定义不是有效的 JavaScript。如果对象的键包含语言中保留的任何特殊字符,则必须将其引用,因为它不会被解析为标识符。例如:Access-Control 相当于 Access - Control,这是一个减法,运算符周围的空格对解析器没有影响。

您给它的值也不是有效的 JavaScript,因为 * 是乘法运算符,它需要两个操作数(左和右)。如果您想要文字值,那么它应该是一个字符串。

const headers = {
    Authorization: `Bearer ${ACCESS_TOKEN}`,
    "Access-Control-Allow-Origin": "*"
};

关于javascript - 对 API 的 JSON 数据的跨源请求 - "You may need an appropriate loader to handle this file type.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740539/

相关文章:

node.js - 从 mongo shell 连接到 MongoDB 部署时连接尝试失败

node.js - CoffeeScript、Node.js、MongoDB 和 JasperReports,有可能吗?

javascript - 如果另一个数组具有相似项,则从数组中删除项

javascript - 在对象的对象中获取数据?

javascript - jquery中json循环后的命令

javascript - 解析具有相同 id 值的所有 JSON 对象

javascript - 传入哈希路径 url 的窗口滚动

javascript - 如果使用 jQuery 在视口(viewport)中可见,如何显示元素? (更新)

javascript - js - 获取带有变量的json

node.js - nodejs 代理没有响应