Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Axios 请求本地静态资源 #48

Open
jtwang7 opened this issue May 30, 2022 · 0 comments
Open

React Axios 请求本地静态资源 #48

jtwang7 opened this issue May 30, 2022 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented May 30, 2022

参考:create-react-app中使用axios请求本地json文件

问题描述

React 中请求本地资源,在项目通过 npm start 启动后,无法成功请求。通过 debug 定位发现请求的路径存在问题。

解决方法

在 React 中请求本地资源时,必须把静态文件放到 public 下才可以请求到。这是因为 axios 请求配置的实际根路径(baseURL)是 http://localhost:3000,项目启动后,axios 会在该根路径的基础上拼接静态资源的路径信息。假设 axios 配置如下:

axios.get('./data/xxx.csv', {
  baseURL: 'http://localhost:3000',
})

那么最终请求静态资源的路径为 http://localhost:3000/data/xxx.csv,而该路径对应的就是 react 项目中的 public 文件夹所在路径。

项目启动后的根目录对应 public 文件夹路径

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant