首页 > 解决方案 > 调用api时反应webpack代理cors问题

问题描述

reactjs 中的错误,当通过 webpack 代理连接到后端时,url 不起作用,即使端点正确,也找不到 404。使用打字稿,我正在使用 axios 在 httpservice 页面中获取我的数据。

  devServer: {
  port: 8083,
  historyApiFallback: true,
  contentBase: paths.public,
  proxy: {
    "/api": "http://localhost:8083",
  },
  headers: {
    "Access-Control-Allow-Origin": "*",
    https: true,
  },
},

mode: "development",

entry: paths.entry,

resolve: {
  extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],
  alias: {
    src: paths.src,
    assets: paths.assets,
  },
},

output: {
  filename: "[name].[chunkhash:8].js",
  publicPath: "/",
},

module: {
  rules: [
    {
      test: /\.m?js/,
      resolve: {
        fullySpecified: false,
      },
    },
    {
      test: /\.tsx?$/,
      use: "ts-loader",
    },
    {
      test: /\.(png|jpg|gif|svg)$/i,
      type: "asset/resource",
    },
  ],
},

plugins: [
  new HtmlWebpackPlugin({
    inject: true,
    template: paths.html,
  }),
],

在获取方面,我这样称呼

import http from "./httpServices";

const apiEndpoint = "/api/item";

function itemUrl(id) {
  return `${apiEndpoint}/${id}`;
}

export const getItemsFromApi = () => {
  return http.get(apiEndpoint);
};

标签: reactjswebpackproxyfetch

解决方案


您忘记添加 pathRewrite: { '^/api': '' }。代理不会覆盖 api 端点。pathRewrite 将 /api 替换为目标

proxy: {
   "/api": {
     target: "http://localhost:8083/",
     pathRewrite: { "^/api": "" },
   },
},

开发服务器文档: https ://webpack.js.org/configuration/dev-server/#devserverproxy


推荐阅读