使用Nuxt 3的Fetch对接Strapi 4登录遇Bad Request错误求排查
Strapi 4 + Nuxt 3 登录功能问题排查与解决方案
一、Fetch实现登录登出是否可行?
完全可行,Nuxt 3 内置的 $fetch 基于原生Fetch封装,完全支持处理Strapi的认证接口,包括登录、登出、用户信息查询等操作。
二、Bad Request错误原因及代码修正
你的代码核心问题是请求体格式错误:Strapi 4 的 /api/auth/local 登录接口不需要将参数包裹在 data 对象中,直接把 identifier 和 password 放在请求体根层级即可。Postman能正常运行是因为你在Postman里没有多余的data嵌套,而代码里多了这一层,导致Strapi无法解析正确的登录参数,进而返回Bad Request。
修正后的完整代码:
<script setup> const userName = ref("") const userPassword = ref("") const createLogin = async () => { try { const response = await $fetch("http://localhost:1337/api/auth/local", { method: "POST", body: { // 直接传递参数,不要嵌套在data中 identifier: userName.value, password: userPassword.value } }) console.log('登录成功!', response) // 可将返回的jwt和用户信息存入Pinia或localStorage,用于后续接口鉴权 } catch (error) { console.error('登录失败:', error.response?._data || error.message) } } </script> <template> <div> <div>User: <input type="text" v-model="userName" /></div> <div>Password: <input type="password" v-model="userPassword" /></div> <button @click="createLogin">Log In</button> </div> </template>
额外优化建议:
- 密码输入框改为
type="password",避免明文显示 - 加入
try/catch捕获错误,方便调试查看具体报错信息 - 登录成功后,将Strapi返回的
jwt和user数据存入状态管理工具(如Pinia)或本地存储,后续接口请求时携带鉴权头
三、登出功能实现示例
若需实现登出,除了清除本地存储的token和用户信息,还可调用Strapi的登出接口(若启用了token黑名单机制):
const logout = async () => { try { await $fetch("http://localhost:1337/api/auth/logout", { method: "POST", headers: { Authorization: `Bearer ${你的jwtToken}` } }) // 清除本地存储的鉴权数据 localStorage.removeItem('jwt') // 跳转至登录页或首页 navigateTo('/login') } catch (error) { console.error('登出失败:', error) } }
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

