我正在使用 react.js 和 musixmatch api 构建一个简单的歌词查找器应用程序。当我请求 api 时,我在控制台中收到此错误Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)
这是我的 componentDidMount() 函数
import React, { Component } from 'react';
import axios from 'axios';
const Context = React.createContext();
export class Provider extends Component {
state = {
track_list: [],
heading: "Top 10 Tracks"
}
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=${
process.env.REACT_APP_MM_KEY}`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
render() {
return (
<Context.Provider value={this.state} >
{this.props.children}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;
答案 0 :(得分:0)
状态码 403 表示您未获得授权。您可能输入了错误的 api 密钥,或者您的 process.env 不起作用(尝试直接输入 api 密钥!)。
你确定你需要 cors-anywhere 吗?你试过没有吗?
编辑:
当您简单地将带有您的密钥的 url 输入到浏览器中时(没有汽车-任何地方),您可以测试您的 api 密钥是否有效,如下所示:
编辑 2:
这有效,当我在 React 应用程序中尝试时:所以问题一定出在你的 process.env 实现上。
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=your_api_key`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}