React与Laravel通过baseURL连接时请求URL异常致404问题求助
React + Laravel 跨域请求URL异常拼接导致404错误
我在尝试用baseURL配置Axios连接React前端和Laravel后端时,出现了URL异常拼接的问题,最终请求地址变成了http://localhost:3000/://localhost:8000/api/users,返回404 Not Found错误,无法获取后端数据。但直接在浏览器访问localhost:8000/api/users可以正常拿到JSON数据。
相关代码如下:
Axios配置文件:
import axios from 'axios'; export default axios.create({ baseURL: "http:://localhost:8000/api", headers:{ "Content-type":"application/json" } })
React组件代码:
import { useEffect, useState } from "react"; import env from '../env' function Home() { const [users,setUsers] = useState([]); useEffect(()=>{ fetchAllUsers(); },[]); const fetchAllUsers =()=>{ env.get('/users').then(res=>{ setUsers(res.data); }) } return ( <> <h2>User View</h2> <table className="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> {users.map((user,index)=>( <tr key={user.id}> <td>{index}</td> <td>{user.name}</td> <td>{user.email}</td> <td>Edit</td> </tr> ))} </tbody> </table> Home Page </> ); } export default Home;
问题根源
你的Axios配置里baseURL写了两个冒号:http:://localhost:8000/api,这是无效的URL格式。Axios识别到这个baseURL不合法时,会把它当作相对路径处理,所以最终和React所在的域名http://localhost:3000拼接,就出现了奇怪的错误URL。
修复方法
把baseURL里的多余冒号去掉,改成正确的HTTP协议格式:
import axios from 'axios'; export default axios.create({ baseURL: "http://localhost:8000/api", // 移除一个多余的冒号 headers:{ "Content-type":"application/json" } })
修改后,Axios会正确拼接请求地址为http://localhost:8000/api/users,即可正常获取Laravel后端返回的数据。
内容的提问来源于stack exchange,提问作者Joyanta sarkar
相关产品推荐
相关产品推荐

