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

Nit*_*mar 5 javascript vue.js nativescript axios nativescript-vue

我正在尝试在需要API调用的Nativescript-vue后端laravel框架的位置上构建一个小型应用程序,以获取相关数据。例如,如果用户要登录,则需要通过api验证其凭据,oauth/token因此我尝试通过以下axios代码进行调用:

我的settings.js文件包含。

export const authHeader = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}
Run Code Online (Sandbox Code Playgroud)

这是在我的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')
})
Run Code Online (Sandbox Code Playgroud)

当我尝试使用命令进行构建时,tns debug android --bundle得到的提示chrome-devtools是:

api被调用

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

标头

如您所见,我console.log在应用程序内部,向我显示:

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')
});
Run Code Online (Sandbox Code Playgroud)

我得到了相同的结果,而且我从服务器端ex http://confidenceeducare.com/oauth/token尝试了api,它恰好是相同的。普通Vue应用程序将api称为“完美”。我猜该nativescript应用程序存在一些问题。我是否需要导入更多内容?我坚持下去。

如果有人认为我的api端点坏了,我尝试使用示例中提到的网址,即https://httpbin.org/post

http

和:

在此处输入图片说明

当我检查其中的api在postman那边工作时,至少得到一个响应,并带有状态码:

邮递员回应

编辑2: 供参考的github仓库https://github.com/nitish1986/sample_mobile_app

Man*_*noj 5

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

如果您使用的是Android 9或更高版本,你还没有启用,可能会失败useCleartextTraffic在你application的标签AndroidManifest.xml

<application 
        android:usesCleartextTraffic="true"
        android:name="com.tns.NativeScriptApplication"
Run Code Online (Sandbox Code Playgroud)

借助iOS,由于您尚未启用应用传输安全性,因此也会失败。只是为了允许您的应用程序中的所有Http通信,您必须将以下密钥添加到您的info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
Run Code Online (Sandbox Code Playgroud)

如果您只想允许特定的域,请使用NSExceptionDomains键并列出端点。