我正在尝试在 Nativescript-vue
上构建一个小型应用程序,其中我有用于 api 调用的后端 laravel
框架,需要调用它来获取相关数据.例如,如果用户想要登录,他需要通过 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
,它向我显示:
更深入地研究它,我可以看到正在传递 header ,但这些只是临时的:
如您所见,我的应用程序中有 console.log
,它向我显示:
即使在编译时我也会遇到以下错误:
指导我如何实现这一目标。谢谢。
编辑:
同样我使用了nativescript的
自己的http
documentation像这样:
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')
});
我得到了相同的结果,而且我尝试了来自服务器端 ex http://confidenceeducare.com/oauth/token 的 api它恰好是一样的。正常的 Vue
应用程序调用 api 非常好。我猜 nativescript
应用程序有问题。我需要导入更多东西吗?我坚持下去。
如果有人认为我的 api 端点已损坏,我尝试使用示例中提到的 url,即 https://httpbin.org/post
:
和:
当我在 postman
中检查我的 api 时,它在那里工作,我至少得到了一个带有状态代码的响应:
编辑 2: 供引用 github 存储库 https://github.com/nitish1986/sample_mobile_app
最佳答案
我使用 Android 8.0 测试了您在 Github 中共享的完全相同的项目,它运行良好。 axios 调用命中错误 block ,因为响应状态 (error.response.status
) 是 401 并且数据 (error.response.data
) 返回与您看到的完全相同的响应来自 postman 。
如果您使用的是 Android 9 或更高版本,它可能会失败,因为您没有在 AndroidManifest.xml
中的 application
标签上启用 useCleartextTraffic
>.
<application
android:usesCleartextTraffic="true"
android:name="com.tns.NativeScriptApplication"
对于 iOS,它也会失败,因为您没有启用应用程序传输安全性。为了允许您的应用程序内的所有 Http 通信,您必须将以下键添加到您的 info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
如果您只想允许特定域,则使用 NSExceptionDomains
键并列出端点。
关于javascript - 如何在 Nativescript 应用程序中调用 axios/api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184243/