如何在Redux ToolKit Query请求中移除URL前缀的localhost网关
问题根因
你配置的baseUrl没有添加https://协议前缀,浏览器会将无协议的域名识别为当前站点下的相对路径,因此自动拼接了当前运行站点的http://localhost:3000前缀,属于前端路径解析的常规规则,和RTK Query本身逻辑无关。
解决方案
直接修改weatherApi中baseQuery的baseUrl配置,补全协议头即可:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' export const weatherApi = createApi({ reducerPath: 'weatherApi', // 补全https协议头即可 baseQuery: fetchBaseQuery({ baseUrl: `https://api.openweathermap.org/data/2.5` }), endpoints: (builder) => ({ getWeather: builder.query({ query: city => `/weather?q=${city}&appid=${API_KEY}`, // 额外注意:OpenWeatherMap接口返回的原始数据没有外层data包装,不需要取response.data,直接返回response即可,否则会拿到undefined transformResponse: (response) => response, }) }) }) export const { useGetWeatherQuery } = weatherApi
修改后重新运行项目,请求路径就会变为正常的https://api.openweathermap.org/data/2.5/weather?q=dublin&appid=${你的密钥},不会再拼接localhost前缀。
内容的提问来源于stack exchange,提问作者groul
相关产品推荐
相关产品推荐

