React http-proxy-middleware proxy not working - reactjs

Hi I been trying the proxy solution to avoid the cors problems in myapp but it doesn't seem to work, i restarted my machine so many times and that made no difference. Basically myapp using fetchApi to call another domain (localhost:8080) which is a SpringBoot application endpoint. I added in package.json "proxy": "http://localhost:8080/" but the api still return calls with localhost:3000 and i tried setupProxy.js but i faced same issue....Am i missing anything else ! any help would be appreciated...
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/oauth",
createProxyMiddleware({
target: "http://localhost:8080",
changeOrigin: true,
secure: false,
logLevel: "debug",
})
);
};

I removed the {} on createProxyMiddleware and it started working.
Thanks

Related

How to proxy request in Docusaurus v2?

I'm trying to config my Docusaurus web app to proxy the request to my api endpoint. For example, if I make a fetch request in my app fetch(/api/test), it will proxy the request from localhost:3000/api/test to my {{api_endpoint}}/api/test, but I'm still struggling to do it.
What I've done:
add a proxy field in package.json
create a setupProxy.js in the src folder
These 2 are based on the Proxying API Requests in Development
Another approach way is I created a custom webpack plugin and add it to the Docusaurus config
Does anyone have experience on this problem ? Thanks for reading, I really appreciate your help.
I went down the exact same path. Ultimately Docusaurus runs its Webpack dev server under the hood which is why the proxy field and setupProxy.js were not working as expected. I was able to get the outside API call by proxy and solved CORS errors by creating a Docusaurs plugin like you are attempting. Adding the "mergeStrategy" and "changeOrigin" were the keys to getting it all working.
// plugins/webpack/index.js
module.exports = function (context, options) {
return {
name: "cusotm-webpack-plugin",
configureWebpack(config, isServer, utils) {
return {
mergeStrategy: { "devServer.proxy": "replace" },
devServer: {
proxy: {
"/YOUR_COOL_ROUTE": {
target: "https://YOUR_COOL_API/",
secure: false,
changeOrigin: true,
logLevel: "debug",
},
},
},
};
},
};
};

Cannot access firebase storage with cloudways server. No 'Access-Control-Allow-Origin'

Thats the error on console
How can access that data without getting blocked by cors in server cloudways? Im using react.js
You can write a little proxy for your react application that is used in your dev environment.
For this, you can simply use the package http-proxy-middleware:
https://www.npmjs.com/package/http-proxy-middleware
After installation, you need to create a file, e.g. "setupProxy.js" in your
/src directory with the according settings. Something like this can work:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'/storage',
createProxyMiddleware({
target: 'https://firebasestorage.googleapis.com',
changeOrigin: true,
pathRewrite: {
'/storage': '/',
},
})
);
};
In you app, you then need not to call https://firebasestorage.googleapis.com/whateverpath, but your proxy: /storage/whateverpath.

How can I get rid of a URL in a fetch (to use kind of a variable instead)?

I have this function for submitting code (see gist https://gist.github.com/constantinscum/4ed753dcd681b4758a8500e4b53d925c) and I don't want to write that //https: in every source file. I was thinking about a global variable but it might be a more elegant solution for this. Do you have any idea how to do that?
I want to get rid of the localhost domain URL because it will change after the app will be deployed on a server. Thank you!
You should use a proxy to the backend api url, this will allow you to just write the api url without adding server name / domaine
in development you can create setupProxy.js and use http-proxy-middleware to redirect all api calls to the server
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = app => {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3001',
changeOrigin: true,
}),
);
};
and your fetch call will look something like this
fetch('/api/code/add')
you can read more about setup proxy Here
and for production it will depend on the tools you will use, (Nginx, Node, ...)
Probably this will not give a direct answer to your question, but its a good practice,
What we normally do is create a separate file for api details
for ex:
api.js
//REACT_APP_SERVER_URL is a env variable in .env file
const rootUri = process.env.REACT_APP_SERVER_URL
? process.env.REACT_APP_SERVER_URL
: 'http://localhost:3001';
const apiVersion = 'v1';
const apiBasePath = `${rootUri}/api/${apiVersion}`; //this is the base path
export const userApis = {
all: {
url: `${apiBasePath}/users`,
method: 'GET',
},
update: {
url: `${apiBasePath}/user`,
method: 'POST',
},
};
this is how we use it
const fetchAllUser = () => {
const api = userApis.all;
fetch(api.url, {
method: api.url.method,
body: JSON.stringify(request)
}...
You can make the request without the http://localhost:3000 part. It will still find it. Try and let me know if it works.
I noticed you added the React tag to your question.
If your back-end and front-end are running on different ports you have to setup a proxy in your front-end package.json file. It would look something like this:
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:3000/api",
"dependencies": {...},
...
}
Now you can fetch("/code/add") for example and if react does not find that route defined on the front-end it will look in proxy routes and do this by itself: fetch("http://localhost:3000/api/code/add")

React app with Rocket backend giving ECONNREFUSED when using proxy

I'm trying to make a web app using rocket for the backend and react for the frontend. However, when I try to make a proxy I keep getting rayk#pop-os:~/repos/homrs/frontend$ curl http://localhost:3000/api Proxy error: Could not proxy request /api from localhost:3000 to http://localhost:8000 (ECONNREFUSED).
The things I've currently tried are adding "proxy": "http://localhost:8000" to my package.json in the application and I've always tried configuring the proxy manually as suggested here https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually.
Here is the backend code I'm using to test:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
fn main() {
rocket::ignite().mount("/api", routes![index]).launch();
}
Here is the setupProxy.js I attempted to use
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
I also have attempted to use http://localhost:8000 and http://localhost:8000/. I have also tried changing the rocket port from 8000 to 3001 and that also did not work.
Edit: Here is a link to the github repo: https://github.com/GimpFlamingo/homrs
The people here: https://github.com/plouc/mozaik/issues/118 were having a similar issue.
I was able to reproduce your issue and found adding address = "127.0.0.1" to Rocket.toml and then setting "proxy" to "http://127.0.0.1:8080" fixed it for me!

http-proxy-middleware not proxying to index page of other server?

I have two servers running on Docker. One is the react frontend at localhost:3000 while the backend runs at localhost:9000. When I go to localhost:3000/api, I want to get to the index page of the backend, which is localhost:9000.
Created a setupProxy.js file in the myApp folder created through create-react-app:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://backend:9000' }));
};
When I go to localhost:3000/api, I get sent to localhost:9000/api instead of localhost:9000.
http-proxy-middleware has a pathRewrite option, see the documentation.
In your particular case:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', {
target: 'http://backend:9000',
pathRewrite: {'^/api' : ''}
}));
};
this should normally rewrite localhost:3000/api/endpoint to localhost:9000/endpoint.
Note that there is also a router option for more tailored behavior.

Resources