如何在Nativescript应用程序中调用axios / api调用

时间:2019-03-15 13:57:16

标签: javascript vue.js axios nativescript nativescript-vue

我正在尝试在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,它向我显示:

api being called

更深入地研究它,我可以看到标头正在传递,但它们只是临时的:

headers

如您所见,我的应用程序中有console.log,向我显示:

console.log

即使在编译时,我也会遇到以下错误:

compiling error

指导我如何实现这一目标。谢谢。

编辑:

类似地,我使用nativescript's自己的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端点损坏,我尝试使用示例中提到的网址,即https://httpbin.org/post

http

和:

enter image description here

当我在postman中检查我的api时,该API在那儿工作,我至少收到一条响应,其中包含状态码:

postman response

修改2: 供参考的github仓库https://github.com/nitish1986/sample_mobile_app

2 个答案:

答案 0 :(得分:2)

我测试了与Android 8.0在Github中共享的完全相同的项目,它运行良好。由于响应状态(error.response.status)为401,数据(error.response.data)返回与Postman完全相同的响应,因此axios调用会击中错误块。

如果您使用的是Android 9或更高版本,则可能由于未在useCleartextTraffic的{​​{1}}标签上启用application而失败。

AndroidManifest.xml

在iOS上,由于您尚未启用应用传输安全性,因此也会失败。只是为了允许应用程序中的所有Http通信,您必须将以下密钥添加到<application android:usesCleartextTraffic="true" android:name="com.tns.NativeScriptApplication"

info.plist

如果只想允许特定的域,请使用<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> 键并列出端点。

答案 1 :(得分:0)

问题与axios的导入方式有关。试试:

import axios from 'axios/dist/axios'

这也解决了Module not found: Error: Can't resolve 'net' in...错误。

通常在导入软件包时,我的请求失败,返回错误

Error in v-on handler (Promise/async): "Error: Request failed with status code null"