score:2

Accepted answer

Since you're using webpack-dev-server you can use the proxy option DevServerProxy.

Your configuration will look like this:

// webpack.config.js
devServer: {
    proxy: {
      '/internal': 'http://localhost:1337'
    }
  }

Since I can't see your express routes on your question I'm speculating about the proxy route if your API lives on /internal endpoint then you should modify your React code like this:

const response = await fetch('/internal/provider/check_email_exist', {
   method: 'POST',
   headers,
   body,
})

As you can see I ommited the https://localhost:1337 because the proxy option from webpack-dev-server will handle this and it will redirect to http://localhost:1337. Hope this will help you. Cheers, sigfried.

EDIT

As the comment on your question pointed out you should set the headers on your express server, not the client, for this task you can use the cors-middleware package.

score:0

Maybe this can help if you face with preflight errors.

My full config:

const cors = require('cors');
const express = require('express');
const { createProxyMiddleware: proxy } = require('http-proxy-middleware');

...
const logLevel = 'info';
const ip = require('ip').address();

const proxyOptions = {
  xfwd: true,
  target,
  changeOrigin: true,
  logLevel,
  cookieDomainRewrite: {
    '*': 'localhost',
  },
  headers: {
    'X-Forwarded-For': ip,
    'X-Node': 'true',
  },
};

const backNginxApp = express();

backNginxApp.use(
  cors({
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200,
    credentials: true,
  })
);
backNginxApp.use('/api', proxy(proxyOptions));

API: const target = 'https://someapi.com'

Local development running at: http://localhost:3000


Related Query

More Query from same tag