I've struggled for hours now trying to get http-proxy-middleware to work but what ever I do it just won't work.
This is my setUp.js file (located in src)
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware('/api', {
target: 'http://catfact.ninja/fact',
changeOrigin: true,
pathRewrite: { '^/api': '' },
logLevel: 'debug',
})
);
};
Here is how I fetch
fetch('/api', {
method: 'GET',
})
.then(response => {
console.log(response)
response.json()
})
.then(data => {
console.log('Success: ', data);
})
.catch((error) => {
console.error('Error: ', error);
});
During start and fetching I get these messages
[HPM] Proxy created: /api -> http://catfact.ninja/fact
[HPM] Proxy rewrite rule created: "^/api" ~> ""
[HPM] Subscribed to http-proxy events: [ 'error', 'close' ]
Starting the development server...
Compiled successfully!
You can now view app in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.0.90:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
webpack compiled successfully
[HPM] Rewriting path from "/api" to ""
[HPM] GET /api ~> http://catfact.ninja/fact
[HPM] Rewriting path from "/api" to ""
[HPM] GET /api ~> http://catfact.ninja/fact
This is the error I get Chrome's console
When using the "proxy" setting in package.json it works fine but since I need to add proxy for a websocket as well I need to use the setupProxy.js file.
I really don't know what I'm doing wrong, I've searched for a solution for a very long time and nothing I do gets me closer to figuring out what is wrong.
I found the problem. Apparently there is a bug in "pathRewrite" in the current version of http-proxy-middleware which causes it not to work properly. This is fixed in the next version according to the developer.