javascript - 如何在 Nativescript 应用程序中调用 axios/api 调用
问题描述
我正在尝试Nativescript-vue
在我拥有laravel
用于 api 调用的后端框架的地方构建一个小型应用程序,需要调用该框架来获取相关数据。例如,如果用户想要登录,他需要通过 api 验证其凭据,oauth/token
所以我试图通过以下方式调用它axios
是我的代码:
我的settings.js
文件包含。
export const authHeader = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
这是在我的 axios 调用中导入的:
const postData = {
grant_type: 'password',
username: user.email,
password: user.password,
client_id: clientId,
client_secret: clientSecret,
scope: '',
provider: provider
}
const authUser = {}
axios.post(authUrl, postData, {headers: authHeader}).then(response => {
console.log('Inside oauth/token url')
if(response.status === 200)
{
console.log('response received')
}
})
.catch((err) => {
if(err.response.status === 401){
reject('Validation error')
}
else
reject('Something went wrong')
})
当我尝试使用命令构建时,tns debug android --bundle
我得到chrome-devtools
了显示:
更深入地研究它,我可以看到标题正在被传递,但这些只是临时的:
如您所见,我console.log
在我的应用程序中向我展示了:
即使在编译时,我也会收到以下错误:
指导我如何实现这一目标。谢谢。
编辑:
同样,我使用了nativescript's
自己的http
文档,如下所示:
const httpModule = require("http");
httpModule.request({
url: "http://iguru.local/oauth/token",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
grant_type: 'password',
username: this.user.email,
password: this.user.password,
client_id: 'check',
client_secret: 'check',
scope: '',
provider: 'check'
})
}).then((response) => {
// Argument (response) is HttpResponse
console.log('Action called')
if(response.status === 200)
{
console.log('Response recieved')
}
}, (e) => {
console.log('Something went wrong')
});
我得到了相同的结果,而且我从服务器端尝试了 api,例如http://confidenceeducare.com/oauth/token它恰好是相同的。正常Vue
的应用程序调用 api 非常好。我猜这个应用程序有问题nativescript
。我需要导入更多的东西吗?我坚持下去。
如果有人认为我的 api 端点已损坏,我尝试使用示例中提到的 url,即https://httpbin.org/post
:
和:
当我检查我的 api 在postman
那里工作时,我至少收到一个带有状态码的响应:
编辑 2: 供参考 github 存储库https://github.com/nitish1986/sample_mobile_app
解决方案
我使用 Android 8.0 测试了您在 Github 中共享的完全相同的项目,它运行良好。axios 调用命中错误块,因为响应状态 ( error.response.status
) 为 401,并且数据 ( error.response.data
) 返回与您从 Postman 看到的完全相同的响应。
useCleartextTraffic
如果您使用的是 Android 9 或更高版本,它可能会失败,因为您尚未application
在AndroidManifest.xml
.
<application
android:usesCleartextTraffic="true"
android:name="com.tns.NativeScriptApplication"
使用 iOS 也会失败,因为您没有启用应用程序传输安全性。只是为了允许您的应用程序中的所有 Http 通信,您必须将以下密钥添加到您的info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
如果您只想允许特定域,请使用NSExceptionDomains
key 并列出端点。
推荐阅读
- google-cloud-platform - 如何修复 CloudRun 错误“请求被中止,因为没有可用的实例”
- class - 从模板派生的 C# 类
- postgresql - JOIN vs SubQuery:为什么子查询性能不应该胜出?
- c# - 使用 Parallel.Foreach 读取目录中的所有文件会使我的 ide 崩溃
- java - 如何在 react-native 中使用来自不同类的方法
- groovy - 从spring cloud合约中的response中引用请求查询参数
- php - PHP DateTime->diff() 无法正常工作
- r - 从单个列中识别模糊重复并使用 R 创建包含模糊重复记录的子集
- spring-integration - 使用 spring-boot-starter-integration 处理来自远程动态源的大文件
- python - Python内部函数变量范围