react-native - React Native fetch 返回 404 但邮递员执行 200 ok
问题描述
我正在将 Spotify web api 集成到反应原生应用程序中。我对 React Native fetch 有问题。当我在 Postman 中调用 api 时,我得到 200 响应代码,但如果我在模拟器(react native)中运行它,我得到 404 错误代码。我还在 chrome 控制台中编写了 fetch 请求,它运行良好,但在 react native 中它不起作用。
我正在运行的代码:
let response = await fetch(`https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US`, {
method: 'GET',
headers: {
'Accept': 'application/json;charset=utf-8',
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc'
}
});
console.log("response",response.status)
解决方案
我在 React Native v. 0.58.6 中尝试了以下代码
async componentDidMount() {
let spotifyApiUrl = "https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US";
let fetchSettings = {
method: 'GET',
headers: {
'Accept': 'application/json;charset=utf-8',
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc'
}
};
fetch(spotifyApiUrl, fetchSettings)
.then( (response) => response.json() )
.then( (responseJson) => {
console.log(JSON.stringify(responseJson));
})
.catch((error) => {
console.log(error);
});
}
使用以下控制台输出:
{"error":{"status":401,"message":"The access token expired"}}
您是否尝试过插入实际设备以查看是否是模拟器问题?如果您使用真实设备,请记住在运行“react-native run-android”之前在 adb 上转发 tcp 端口
adb reverse tcp:8081 tcp:8081
react-native run-android
推荐阅读
- unity3d - Unity生成OBB并集成到Android原生
- python - 如何跳过逗号和空格,但不改变值
- java - Java 字符串池是如何工作的?Java如何决定是否使用它?
- php - Mysql wokbench db与php的连接
- php - Laravel - 从两列创建最常见的列表
- jquery - 使用嵌套插入时仅显示一条成功消息
- r - 更改刻面环绕中刻面的位置,按年份排序
- ruby-on-rails - 获取 url :local/ads.txt 以重定向到 public/ads.txt 文件
- r - Rails 6.0 操作文本找不到类型为“text/css”的文件“trix/dist/trix”
- ruby-on-rails - 创建对象后如何在 JSON 中包含嵌套关联?