【问题标题】:next.js fetch data from Laravelnext.js 从 Laravel 获取数据
【发布时间】:2022-01-20 10:04:54
【问题描述】:

我正在使用 Laravel 和一个简单的代码编写一个简单的用户注册

public function register()
{
    $this->validate(request(), [
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required'
    ]);

    $user = User::create(request(['name', 'email', 'password']));
    
    auth()->login($user);

    return [
        'status' => true,
        'user' => $user
    ];
}

然后我发送数据表单Next.Js

使用axios:

let config = {
    method: 'post',
    url: `http://localhost:8000/api/register`,
    headers: {
        'Content-Type': 'application/json',
    },
    data: values,
}
axios(config)
.then(json => console.log(json))

没问题,但是我发了一个用过的邮箱,会通过422码,axios抓不到结果

使用fetch:

fetch('http://localhost:8000/api/register', {
    method: "post",
    mode: 'no-cors',
    body: new URLSearchParams(data)
}).then(res => res.json())
.then(json => console.log(json))

也可以,但使用邮箱时,会发送302码,并调用索引/

【问题讨论】:

  • “会通过422码,axios抓不到结果”——为什么不在axios的promise链中加一个.catch(...)呢?跨度>

标签: javascript laravel axios next.js fetch-api


【解决方案1】:

我认为您错过了添加 .catch(...) 以返回错误对象,如文档中的示例 Axios docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2015-02-05
    • 2021-10-09
    • 2021-06-10
    • 2020-05-30
    相关资源
    最近更新 更多