React webpack proxy cors issue when calling the api

Viewed 519

Error in a reactjs , when connecting to the backend end via webpack proxy, the url doesnt work , gives 404 not found even tho the endpoint is correct. working with typescript and I'm using axios to get my data in the httpservice page.

  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,
  }),
],

and on the fetch side I call like so

import http from "./httpServices";

const apiEndpoint = "/api/item";

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

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

you forgot to add pathRewrite: { '^/api': '' }. The proxy is not overwriting the api endpoint. pathRewrite will replace /api with the target

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

DevServer Documentation: https://webpack.js.org/configuration/dev-server/#devserverproxy

Related