You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js+Laravel中使用Fetch传递参数至异步API的正确方法

问题分析与解决方案

你的代码主要存在以下几个问题:

  1. Fetch请求参数传递错误:第一个代码中直接将{email: email}作为fetch的配置项,但fetch的配置对象没有这个字段,无法正确传递参数;且未在第一个then中返回响应体解析结果,导致第二个then的data为undefined。
  2. GET请求使用body无效:第二个代码中GET请求携带body不符合HTTP规范,浏览器会忽略该body;且Request对象只是请求描述,需要通过fetch()执行才能发送请求,直接调用result.json()无意义。

下面提供两种基于Fetch的正确实现方案,适配你的Laravel控制器:

方案一:GET请求(通过URL查询字符串传递email)

前端Fetch代码

const email = this.loginbus.loginemail;

// 构建带查询参数的URL
const requestUrl = new URL('http://localhost:8000/api/checklogin');
requestUrl.searchParams.append('email', email);

await fetch(requestUrl)
  .then(response => {
    // 检查响应状态是否正常
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    // 解析JSON格式的响应体
    return response.json();
  })
  .then(data => {
    console.log('接口返回结果:', data);
  })
  .catch(error => {
    console.error('请求出错:', error);
  });

Laravel控制器适配

控制器中可以直接通过$request->email或$request->query('email')获取URL中的email参数,建议添加参数验证并使用规范响应格式:

public function checklogin(Request $request) {
    // 验证email参数是否合法
    $request->validate(['email' => 'required|email']);
    
    $getVerify = Makatibuspartner::where('email', $request->email)->select('email_verified_at')->first();           
    
    if (!$getVerify){
        return response()->json(["status" => 400, "error" => "请输入已注册的邮箱"], 400);
    } else if (is_null($getVerify->email_verified_at)) {
        return response()->json(["status" => 400, "error" => "邮箱未验证"], 400);    
    } else {
        return response()->json(["status" => 200, "message" => "邮箱已验证"], 200);
    }  
}

方案二:POST请求(通过请求体传递email)

前端Fetch代码

const email = this.loginbus.loginemail;

await fetch('http://localhost:8000/api/checklogin', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        // Laravel需要CSRF令牌(若为API路由且已配置无状态认证可省略)
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
    },
    body: JSON.stringify({ email: email })
})
.then(response => {
    if (!response.ok) {
        throw new Error(`请求失败,状态码:${response.status}`);
    }
    return response.json();
})
.then(data => {
    console.log('接口返回结果:', data);
})
.catch(error => {
    console.error('请求出错:', error);
});

Laravel控制器适配

Laravel会自动解析JSON请求体,你的现有逻辑无需修改,同样建议添加参数验证和规范响应格式(如上例)。


内容的提问来源于stack exchange,提问作者babe_engineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:53:13