SvelteKit服务端调用本地Laravel API遇ENOTFOUND错误求助
解决SvelteKit服务端请求本地Laravel API失败的问题
核心问题定位
报错getaddrinfo ENOTFOUND api.laravel.localhost说明Node.js环境(SvelteKit服务端代码运行环境)无法解析api.laravel.localhost这个域名,和你修改的CSRF配置无关。
解决方案步骤
1. 配置本地hosts文件
确保系统hosts文件已将api.laravel.localhost指向本地回环地址:
- Linux/macOS:编辑
/etc/hosts,添加一行:
保存后刷新DNS缓存:127.0.0.1 api.laravel.localhostsudo dscacheutil -flushcache - Windows:编辑
C:\Windows\System32\drivers\etc\hosts,添加同样的行,保存后执行:ipconfig /flushdns
2. 修正fetch请求的代码错误
你把请求方法method写在了headers对象里,这是语法错误,正确写法应将method作为配置的顶级属性:
const endpoint = "http://api.laravel.localhost"; // 若Laravel用自定义端口,需加上,比如http://api.laravel.localhost:8000 export async function load() { let url = `${endpoint}/auth/me` try { const options = { method: "GET", // 移到配置顶级,不在headers内 headers: { 'Accept': 'application/json' } }; const response = await fetch(url, options); // 额外添加:校验请求是否成功 if (!response.ok) throw new Error(`HTTP错误!状态码:${response.status}`); const data = await response.json(); console.log(data); return { user: data }; // 建议返回数据给页面组件使用 } catch (error) { console.error('获取数据失败:', error); return { error: error.message }; // 返回错误信息给页面 } }
3. 验证Laravel API的可达性
- 先在浏览器中访问
http://api.laravel.localhost/auth/me(或对应的IP+端口路径),确认能正常返回JSON数据。 - 若使用
artisan serve启动Laravel,默认地址为127.0.0.1:8000,对应的API地址应为http://127.0.0.1:8000/api/auth/me,可直接用此IP地址测试,规避域名解析问题。
4. 排查虚拟主机配置(若使用)
如果用Nginx/Apache配置了api.laravel.localhost虚拟主机,需确保:
- 虚拟主机根目录指向Laravel的
public文件夹 - 配置文件已正确处理
/api路由 - 服务已重启生效
内容的提问来源于stack exchange,提问作者Bernan Ribeiro
相关产品推荐
相关产品推荐

