Axios从next.js获取对Laravel端点的请求

问题描述 投票:1回答:1

我对laravel端点有以下请求:

axios.get('http://localhost:8000/auth/login', {})
            .then(function (response) {
                console.log(response);
                return {};
            })
            .catch(function (error) {
                return {}
            });

我的laravel端点设置为:

public function index() {
        var_dump('login called.');die;
        return response()->json(
            [],
            200
        );
    }

我启动了我的nextjs服务器(端口3000)和laravel服务器(8000),当我在浏览器中浏览localhost:8000 / auth / login时,我看到“登录名为”。然而,当我做那个axios呼叫时,我得到状态200ok但没有响应数据。

Request URL:http://localhost:8000/auth/login
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade

知道我做错了什么吗?

laravel axios next.js nextjs
1个回答
1
投票

您的代码正确获得响应没有任何问题,您看到“登录已调用”,因为您正在从浏览器访问,因此浏览器具有呈现html的可能性,您可以看到它。

但那个axios调用期望一些json作为回报。如果你稍微调整一下响应:

public function index() {

        return response()->json(
            ['data' =>'Log in called'],
            200
        );
    }

如果你对axios的反应稍微有些吵醒

axios.get('http://localhost:8000/auth/login', {})
            .then(function (response) {
                console.log(response.data);
                return {};
            })
            .catch(function (error) {
                return {}
            });

检查元素打开控制台,你会看到'Log in called'

© www.soinside.com 2019 - 2024. All rights reserved.