javascript - 本地 laravel API 上的 Nativescript-Vue axios 调用错误 [请求失败,状态码为空]

标签 javascript android ios vue.js nativescript

我对 Nativescript 相当陌生,在我的项目中,我试图向我在 http://127.0.0.1:8000/ 上使用 php artisan serve 设置的本地 laravel 服务器发出 http 请求,我使用的是连接的安卓设备,没有模拟器。经过一番阅读,我使用 ipconfig 命令获得了本地 IPv4。

在我的 App.vue 组件中,我使用 axios 向本地 laravel API 端点发出 GET 请求:

这不起作用:

console.log('Firing axios call');
axios.get('http://192.168.1.35:8000/api/posts')
.then((response) => {
    console.log('It worked! /////////////////////////////////////////');
}).catch((err)=>{
    console.log('God dammit',err);
});

但我总是得到错误:
'God dammit' [Error: Request failed with status code null]

在 laravel 中,这是我的 Controller 方法,它响应/api/posts
public function list(Request $request)
    {
        $posts = Post::with(['postcategory','author'])
            ->latest()
            ->paginate($request->input('paginate', 10));

        return response()->json([
            'data' => $posts,
            'pagination' => [
                'total' => $posts->total(),
                'per_page' =>$posts->perPage(),
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'from' => $posts->firstItem(),
                'to' => $posts->lastItem()
            ]  
        ]);
    }

我尝试使用 httpbin 端点并得到响应,它可以工作,但我的 laravel API 永远无法工作......

这确实有效:
axios.get('https://httpbin.org/get')
.then((response) => {
   console.log('success');
   console.log(response.data);
}).catch((err)=>{
   console.log(err);
});

并返回:
{ args: {},
JS:   headers:
JS:    { Accept: 'application/json, text/plain, */*',
JS:      'Accept-Encoding': 'gzip',
JS:      Host: 'httpbin.org',
JS:      'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.4; GT-I9060I Build/KTU84P)' },
JS:   origin: '79.152.179.88, 79.152.179.88',
JS:   url: 'https://httpbin.org/get' }

知道我做错了什么吗?

最佳答案

由于您使用的是 http,因此您需要将其添加到应用程序标签中的 app/App_Resources/Android/src/main/AndroidManifest.xml 中:
android:usesCleartextTraffic="true"

像这样:

<application ...
    android:usesCleartextTraffic="true"

关于javascript - 本地 laravel API 上的 Nativescript-Vue axios 调用错误 [请求失败,状态码为空],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111564/

相关文章:

javascript - 找到射线和球体之间的交点的函数? (Javascript)

android - 将 DateTime 对象 java 转换为 Json 字符串

Android,将外部库导入到NDK

android - 我可以有 3 个 sharedpreferences 文件以及如何读取每个文件吗

iOS 正确使用 @weakify(self) 和 @strongify(self)

ios - UITableView 在用户释放之前重置到开始位置

ios - 我在主视图中写了一个函数。现在,我该如何调用它?

javascript - 奇怪的 jQuery XML 问题

javascript - 搜索栏在几个 Accordion 中查找行

javascript - jquery 是(:visible) for visibility : hidden