You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:45:01