【问题标题】:Axios get request to Laravel endpoint from next.jsAxios 从 next.js 获取对 Laravel 端点的请求
【发布时间】:2018-05-31 05:00:29
【问题描述】:

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

知道我做错了什么吗?

【问题讨论】:

  • 是的die;错了
  • 啊,你是对的,我认为至少应该返回 var_dump。谢谢!

标签: laravel axios next.js nextjs


【解决方案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'

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2021-01-20
    • 2021-04-01
    • 2020-06-27
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多