【问题标题】:Axios fetching data from different url when providing route with paramsAxios在提供带有参数的路由时从不同的url获取数据
【发布时间】:2022-09-29 16:18:16
【问题描述】:

我在代理上运行反应应用程序和节点服务器,当向路由提供参数时,它会从中获取数据http://localhost:3000/confirmation/api/token/1代替http://localhost:3000/api/token/1如果我不向 Confirmation.js 提供任何参数 喜欢 <Route path=\"/confirmation\" element={<Confirmation />} /> 该请求工作正常。

应用程序.js <Route path=\"/confirmation/:token\" element={<Confirmation />} />

确认.js

    const { token } = useParams()
    const [details, setDetails] = useState(null)

    const fetchDetails = useCallback(async () => {
        const response = await axios.get(`api/token/${token}`)
        console.log(response.data)
    }, [token])


    useEffect(() => {
        fetchDetails()
    }, [fetchDetails])

  • 您是否尝试过在api/token/${token} 之前添加/?
  • 我确定 vighnesh 153 的意思是 axios.get(`/api/token/${token}`),即不是相对路径。

标签: javascript reactjs axios


【解决方案1】:

您必须为 api 调用添加基本 url:

axios.defaults.baseURL = 'https://api.example.com'; // your base url
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // auth if needed
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

【讨论】:

【解决方案2】:

您可以通过在请求中使用完整 URL 来解决此问题:

axios.get(`http://localhost:3000/api/token/${token}`)

或者,您可以为 axios 创建一个“助手”。像这样的东西:

const api = axios.create({
    baseURL: 'http://localhost:4001'
})

然后你做例如:

api.get('/v1/users')

将发送请求到:http://localhost:4001/v1/users 从文件中导出此“api”并将其导入到您要使用的任何位置。

【讨论】:

    【解决方案3】:

    由于它不是相对路径,因此将 api/token/${token} 更改为 /api/token/${token} 修复了它。感谢@vighnesh153

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2020-09-09
      • 2020-09-28
      • 2014-05-29
      相关资源
      最近更新 更多