0

This is my setupProxy.js:

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

module.exports = (app) => {
    app.use(
        'http://localhost:8000',
        createProxyMiddleware({
            target: 'https://my-website.com',   // Should request this url
            changeOrigin: true,
        })
    );
};

And this is how I am calling the API:

makeAPICall = (method, headers, data) => {
    let url = new Url('http://localhost:8000/api/get-data');
    let requestOptions = {
        method,
        headers,
        'body': data
    }
    return fetch(url, requestOptions);
}

But the API calls are going to the localhost and not the one that I mentioned in the setupProxy.

I know this is not right way to call apis when using proxy middleware, and we just need to provide a simple string in app.use like '/api1'. But I am not allowed to change the urls, just want to reroute them to new api.

What am I doing wrong here?

Edit: This is how I call makeAPICall function:

headers = {
    'Content-Type': 'application/json',
    'Authorization': `Token ${user.auth_token}`
}
makeAPICall('POST', headers, payload).then(data => handleData(data));
Keshav Bhatiya
  • 295
  • 3
  • 11
  • 1
    And is the React dev server that the proxy is presumably intended for actually running on port 8080? It's 3000 by default. – jonrsharpe Jan 19 '21 at 12:26
  • Yes it's running on 8080 – Keshav Bhatiya Jan 19 '21 at 12:27
  • Important note: You can't send body in a get request. Javascript [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) will ignore it by default. (You can do it in postman, don't let it convince you that you can send body in javascript) – Sinan Yaman Jan 19 '21 at 12:33
  • @SinanYaman fixed it, sending post – Keshav Bhatiya Jan 19 '21 at 12:44

0 Answers0