部署在GitHub Pages的React项目RTK Query GET请求失败排查
我近期使用gh-pages npm包将my-react-app项目部署至GitHub Pages,发现RTK Query在部署环境无法正常工作,但在开发环境可正常运行。以下是相关代码,请教可能的故障原因?
RTK Query查询定义代码
getUni: builder.query({ query: country => ({ url: `http://universities.hipolabs.com/search?country=${country}`, }), transformResponse: responseData => { const resConvert = responseData.slice() .sort((a, b) => a.name.localeCompare(b.name)) .map(each => { return { ...each, id: nanoid() } }); return universityAdapter.setAll(initialState, resConvert) } }) })
React组件调用查询代码
const { isFetching, isSuccess, isUninitialized, isError } = useGetUniQuery(countrySearch, { skip }); const allUni = useSelector(getAllUniversity); if (isUninitialized) { universityData = <h1>Use the drop down menu to generate all Post Secondary options withen your selection</h1> } else if (isError) { universityData = <h1>Error fetching.Please refresh page</h1> } else if (isSuccess) { universityData = allUni.filter(uni => uni.name.toLowerCase().startsWith(uniSearch.toLowerCase())).map(uni => <div key = {uni.id} className = {CardStyles.card} > <h2 className = '' > {uni.name} </h2> <a href = {uni.web_pages[0]} > {uni.web_pages[0]} </a> </div> ) }
可能的故障原因
混合内容限制:GitHub Pages部署的网站使用HTTPS协议,但你的RTK Query请求的API地址是
http://universities.hipolabs.com/(HTTP协议)。现代浏览器会阻止HTTPS页面发起的HTTP请求,这是最可能导致部署环境请求失败的原因。解决方法是将API地址改为HTTPS:https://universities.hipolabs.com/search?country=${country}。base路径配置问题:如果你的项目在GitHub Pages上的部署路径不是根域名(比如
https://username.github.io/my-react-app/),而RTK Query的baseQuery没有正确配置base路径,可能导致请求路径错误。不过你的代码中使用的是绝对URL,这个问题的可能性较低,但可以检查createApi时的baseQuery配置是否正确。transformResponse中的initialState引用问题:如果
initialState是在其他模块定义的,打包部署后可能出现未正确引入的情况。可以检查initialState的导出和导入是否正确,或者尝试在transformResponse内部直接创建初始状态对象,而不是依赖外部的initialState。CORS配置差异:开发环境中React的开发服务器可能自带CORS代理,自动处理跨域请求;但部署到GitHub Pages后,没有代理层,若API服务器的CORS配置存在限制,可能导致请求失败。不过
universities.hipolabs.com是公开API,通常支持CORS,所以这个问题概率较低,但可以通过浏览器开发者工具的Network面板查看请求的CORS错误信息确认。
内容的提问来源于stack exchange,提问作者Kirill

