In some of projects I encountered in create-react-app people use file setuProxy.js which has content like this inside:
const proxy = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
proxy("/api/mobile-activity/ws", {
target: "http://localhost:3001/socket.io",
pathRewrite: { "^/api/mobile-activity/ws": "" },
ws: true,
})
);
app.use(
proxy("/api/vehicle-accident-protocols", {
target: "http://10.1.1.24:7071",
pathRewrite: { "^/api/vehicle-accident-protocols": "" },
})
);
};
I have tried reading about why we need this but most explanations I find online are about how to do this, rarely they explain clearly why we need this. Can someone in easily understandable way explain why we need this file? I am beginner as far as network infrastructure etc is concerned, that's why maybe I am failing to grasp why we need it.
In general, A proxy or proxy server serves as a gateway between your app and the internet. It’s an intermediate server between client and servers by forwarding client requests to resources.
In React, we often use this proxying in the development environment. React uses a create-react-app (webpack dev server) to serve the app in development mode.
Follow this link for more explanations
Related
I am very new to react but my issue is really around strategies for deploying my app to different environments (dev, QA, UAT). My react app makes an api call and I am using a setupProxy.js to define the url for that api, works great locally. I have also built the api and it is hosted separately. My question is how do I change the setupProxy.js so that the url respects the environment it's deployed to. Right now I'm using AzureDevops and Octopus for building and deploying. It seems like everything gets compiled so trying to change this file after is built won't work. Just looking to see what your deployment strategies are.
Here is my setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
const baseUri = 'http://localhost:5000/api';
const proxy = {
target: baseUri + '/UsageRequest/ScreenScrapeErrors',
changeOrigin: true
}
const proxy2 = {
target: 'https://www.stackoverflow.com',
changeOrigin: true,
}
module.exports = function (app) {
app.use(
'/SceenScrapeErrors',
createProxyMiddleware(proxy)
);
app.use(
'/jobs',
createProxyMiddleware(proxy2)
);
};
I would like to modify the baseUri variable as it's getting deployed to the different environments.
This blog post may help you: https://octopus.com/blog/javascript-configuration
You can move your environmental configuration to a JSON configuration file and modify your app to read the values from that value.
Octopus can replace variables in JSON configuration files during deployment using the structured configuration variables feature.
I've been tasked with transitioning a development CRA build to work in production. Currently we use an api proxy in development with a setupProxy.js file as such:
const BACKEND_URL = process.env.BACKEND_URL
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function setupProxy(app) {
app.use(
'/api',
createProxyMiddleware({
target: BACKEND_URL,
changeOrigin: true,
})
)
}
This works as expected in development but this feature isn't meant for production, so I've changed all the API endpoints to make proper use of the backend url (basically going from axios.get(/api/endpoint) to something like axios.get(`${process.env.BACKEND_URL}/api/endpoint`)
From what I can tell now, the calls are pointed at the right place now (before it was erroring out the whole app), but I immediately get a 401/unauthorized error for every call and even my websockets as soon as I log into the app, no data being returned.
Is there a critical part of the transition to prod - and specifically the replacement of the api proxy - that I am missing? It seems like there some sort of token missing that is causing all my calls to fail but there was no such token as part of the setupProxy file? Any direction or help would be appreciated
I am on a project with create-react-app without ejecting.
I wanted to have subdomains on localhost or a fake host for development.
When I added my host in windows hosts file it said invalid host header even if I add HOST=mydevhost.com DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file.
I couldn't make it work without using third party apps so I used Fiddler and it worked as expected now the sites comes up but instantly says:
The development server has disconnected.
Refresh the page if necessary.
The problem is that the fast refresh doesn't work now and I have to refresh the site every time I make a change. Is there anything that I'm doing wrong here? Should I even use something like Fiddler here?
I ended up using react-app-rewired and in config-overrides.js I added the subdomain to allowed host. The final config looks like this:
module.exports = {
webpack: (config, env) => {
return config;
},
devServer: (configFunction) => (proxy, allowedHost) => {
const devServerConfig = configFunction(proxy, allowedHost);
devServerConfig.allowedHosts = ["subdomain.localhost"];
return devServerConfig;
},
};
I thing you can do that from your operating system to point your local domain to your react server, meaning that can create a local domain that points to the app server (host:port).
here's a guideline that may help:
https://www.interserver.net/tips/kb/local-domain-names-ubuntu/
Relevant answers:
How can I develop locally using a domain name instead of 'localhost:3000' in the url with create-react-app?
I am implementing http proxy middleware in to my react app. I want to proxing qa or dev backend services urls from my local .
Example of my dev login url below
https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login
my setupProxy.js
module.exports = function (app) {
app.use('/auth/login' ,createProxyMiddleware({
target: 'https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login',
changeOrigin: true,
})
);
};
I started my app and click the login button and the request got failed with 404 not found error . Not sure why my target is not replacing with my actual http://localhost:9009/auth/login uri to https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login.
Also am not getting proxy created message in my console when we do npm start as well. I am using webpack dev server not react-scripts . If any changes required on webpack side or am i missing anything badly please let me know. I tried small poc it got worked but that is simple without herokuapp things.
It took me some time to understand how the http-proxy-middleware works.
Look at the following diagram from the http-proxy-middleware Docs
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For simple configurations, any request that your front-end does calling an API get observed by a matching pattern on the path section of the above diagram and overwritten with your target configuration, to be exposed in the header of the request as a different URL. This also help you in the development phase locally to avoid the CORS blocking mechanism of the browsers.
Example:
Let's imagine we need to call from our front-end exposed at http://localhost:3000 to an endpoint located at https://localhost:7005/api/WeatherForecast
This type of calls will be blocked in all browsers by CORS.
So, with the following config, you will be able to bypass the cors problem.
const { createProxyMiddleware } = require('http-proxy-middleware');
const context = [
"/api",
];
module.exports = function (app) {
const webApiProxy = createProxyMiddleware(context[0], {
target: 'https://localhost:7005',
secure: false,
changeOrigin: true,
headers: {
Connection: 'Keep-Alive'
},
logLevel: 'debug'
});
app.use(webApiProxy);
};
With this, any request made from http://localhost:3000 will be intercepted by the proxy-middleware and if it finds a /api in some part of the path will be changed to https://localhost:7005/api and also concatenate the rest of your original path following the /api.
So finally, your front-end will be asking things from http://localhost:3000 but all the request will arrive to https://localhost:7005 as if they were request by https://localhost:7005 and this will fix the Cors problem coz your requesting and responding from the same origin.
I Guess your can fix your problem by writting your config this way:
module.exports = function (app) {
app.use('/auth/login' ,createProxyMiddleware({
target: 'https://dev.sju.uk/auth/login',
changeOrigin: true,
headers: {
Connection: 'Keep-Alive'
},
})
);
};
Bare in mind, this libray not only can help you with the CORS problem but also to perform hundred of things for any request/response like change arguments from the body, add things to the body, add headers, perform operations before the request aka logging what's requested, perform operations on the response aka logging again what has returned, etc, etc.
Hope this will help to resolve your issue!
I have a React app that pulling data via Rest API from a different domain.
In my development env in order to work around this, I am using http-proxy-middleware.
module.exports = function (app) {
app.use(
createProxyMiddleware("/shabbat", {
target: "https://www.hebcal.com",
changeOrigin: true
})
)
}
Since I am using Firebase to host my web app I need to handle this via Firebase but can't figure it our how to properly configure.
I would appreciate it if someone can share a working example.
Thank you
i also got this error, i changed to use another https://xxx api to test,then worked well, so i guess this issue is due to firebase's settings, but i haven't found the solution