4

Into my component

axios.post('/api/' + 'create', {
  name: 'new name'
}, 
{
                headers:
                {
                    'Content-Type': 'application/json'
                }
}
)

into setupProxy.js , created from third part official instruction https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(proxy('/api/', {
        target: 'http://my-api.com/',
        changeOrigin: true
    }));
};

When i call method with axios from my app into browser console write POST http://localhost:3000/api/create 404 (Not Found)

I tryed to write /api/* and /api/** into configuration http-proxy-middleware , but it did't help me.

What it does't work?

GreenFed
  • 57
  • 2
  • 7

2 Answers2

1

Please try using below code, with http-proxy-middleware version 1.0.0 onwards, you cannot use proxy as the name.

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
  app.use(createProxyMiddleware('/api',
  { target: 'http://localhost:3001/' 
  }));
}

Note: found this from one of the PR discussions here: https://github.com/facebook/create-react-app/issues/8550

Mital Vora
  • 2,199
  • 16
  • 19
0

I know its late and I came across the same issue. Keeping what worked for me so that others can give it a try.

I proxied this endpoint - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
    app.use(createProxyMiddleware('/api2', {
        target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
        changeOrigin: true,
        pathRewrite: { '^/api2': '' }
    })
    );
}

Your .js file

triggerCORSCall() {
    axios.get(`/api2/Customers?$format=json`)
      .then(response => {
        alert('Success');
      }).catch(error => {
        alert('Failure');
        console.log(error);
      })
  }
Anand
  • 408
  • 2
  • 14