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

时间:2017-12-17 19:08:49

标签: laravel axios next.js nextjs

我对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

知道我做错了吗?

1 个答案:

答案 0 :(得分: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'