Cannot proxy requests with craco config - reactjs

I am trying to proxy requests with craco config. however the proxy seems to be ignored. Why is it not working?
I have a create-react-app project that I started using:
npx create-react-app check-proxy-config --template typescript
and I've added craco to it:
npm i -D #craco/craco
In addition I defined a proxy in craco.config.cjs file:
module.exports = {
webpack: {
devServer: {
logLevel: "debug",
proxy: {
"/api": {
target: "https://<any Domain whatsoever>",
logLevel: "debug",
secure: true, // false
changeOrigin: true, //false
bypass: function(req, res, options) {
console.debug("bypass");
},
onProxyReq: function(proxyReq, req, res) {
console.debug(`Proxying request: ${req.originalUrl} => ${proxyReq.path}`);
}
}
}
},
The request I'm sending from the browser is:
http://localhost:3000/api/something
None of the console.debug statements is printed. Why? how can I make the proxy work?

The configuration worked after checking in the backend server i was able to ensure there was no issue with the config, hoewever the "on" methods (i.e. onProxyReq, etc) are not being called

Related

Nx advanced reverse proxy configuration

Migrating a react application to an Nx integrated workspace, and having an issue with advanced proxy configuration.
I understand that for a simple proxy...
Specify the proxy.conf.json file
"serve": {
"executor": "#nrwl/webpack:dev-server",
"defaultConfiguration": "development",
"options": {
"verbose": true,
"buildTarget": "ydsca:build",
"hmr": true,
**"proxyConfig": "apps/ydsca/proxy.conf.json",**
"ssl": true,
"sslKey": "certs/localhost.key.pem",
"sslCert": "certs/localhost.crt.pem"
},
Implement the proxy.conf.json file, e.g....
{
"/caconnect/common/*": {
"target": "https://127.0.0.1:9443",
"secure": false,
"logLevel": "debug"
}
}
This works without any issues, however, the current React application uses "http-proxy-middleware" and a more advanced setupProxy.js file (wildcard matching such as "/**/common/" for any patch that contains /common/):
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
[
'/**/common/',
'/**/commonClassic/',
'/**/ydscaCommon/',
'/ymca',
'/staff'
],
createProxyMiddleware({
//Must use 127.0.0.1 as for some reason, localhost stopped working in node versions > 16
target: 'https://127.0.0.1:9443',
//Necessary for https with self signed certificates
secure: false,
changeOrigin: false,
//Additional logging stuff!
onProxyReq: function onProxyReq(proxyReq, req, res) {
// Log outbound request to remote target
console.log('--> ', req.method, req.path, '->', proxyReq.baseUrl + proxyReq.path);
},
onError: function onError(err, req, res) {
console.error(err);
res.status(500);
res.json({error: 'Error when connecting to remote server.'});
},
//logLevel: 'debug'
})
);
};
How can the same advanced proxying be configured in Nx?
Tried changing proxyConfig": "apps/ydsca/proxy.conf.json" to proxyConfig": "apps/ydsca/setupProxy.js", but it doesn't seem to like javascript files for proxy configuration!
Any suggestions?
Thank you.

Vite proxy is fetching clientside files

I'm trying to migrate my react project from webpack to vite and I'm facing this issue with proxies:
I've configured my proxy like so:
port: 8000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/graphql': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
But if I use it like that, then vite starts requesting localhost:8080/api for clientside files like localhost:8080/api/index.ts which throws a MIME type error.
What’s the cause for this behavior and how can I fix it? The http-proxy documentation offers no details(which is what Vite uses)

CRA - how to proxy all requests but a specific one?

create-react-app docs says you can configure your proxy objects manually. I'm following the http-proxy-middleware docs on matching
to exclude a specific route but haven't got it to work.
Basically I'm serving my app from the /app route instead of root. So I want the following to happen:
/app/api proxies to http://localhost:3001, my backend service
All requests that does NOT start with /app proxy to http://cloud.my-app.com
This is what I've tried so far with no luck:
"homepage": "https://cloud.my-app.com/app",
"proxy": {
"/app/api": { // Works
"target": "http://localhost:3001"
},
"!/app/*": { // Does not work
"target": "https://cloud.my-app.com",
"secure": false
}
},
What am I missing?
Add the below as your proxy:
"proxy": {
"/app/api":{
"target":"http://localhost:3001",
},
"/.*/":{
"target":"https://cloud.my-app.com",
"secure":"false",
"changeOrigin": true
}
}

webpack-dev-server proxy not working

My app uses a Python backend so when I'm running locally I need to proxy my requests to a different port than what Webpack is running on.
I've tried several different ways of making this work:
devServer: {
contentBase: outDir,
proxy: [
{
path: "**",
target: "http://localhost:8000",
secure: false,
bypass: function(req, res, options) {
if(req.url === '' || req.url === '/') {
res.statusCode = 302;
res.setHeader('Location', '/a/');
return '/a/';
}
var frontend = new RegExp("^\/$^|\/a\/index\.html|^\/a\/|^\/a$|^\/styleguide");
if (frontend.test(req.url)) return req.url;
}
}
],
// serve index.html for all 404 (required for push-state)
historyApiFallback: true,
},
And this:
proxy: [{
context: '/',
target: 'http://localhost:8000',
}],
Both of those will at least show a message similar to this when it starts up: [HPM] Proxy created: ** -> http://localhost:8000. When I look at the docs and do something like this, it doesn't work either (I don't even get a message about the proxy running):
proxy: {
"/": "http://localhost:8000"
}
Is there something obvious I'm doing wrong? I'be been trying every combination that I can think of to make it work.
Try to add changeOrigin: true. Don't forget to change API pattern.
proxy: {
'/api/**': {
target: 'http://localhost:8000',
secure: false,
changeOrigin: true
},
}

Using Protractor with proxypass-based AngularJS app

I'm using Protractor to implement end-to-end tests on my AngularJS app using Grunt, and my app does use proxy pass to handle API calls. As a result, when running tests, API calls fail because http://localhost:9000/api is not handled.
I tried the grunt-connect-proxy plugin to handle /api proxy pass but it simply redirects (HTTP code 301) localhost:9000/api to myserver.com/api, and doesn't mimic the behaviour of a proxy pass (and the app doesn't work either).
Here's the Gruntfile configuration:
connect: {
options: {
port: 9000,
hostname: 'localhost',
base: ['<%= globals.appFolder %>/'],
logger: 'dev',
}
},
protractor: {
options: {
configFile: 'tests/e2e/protractor.config.js',
keepAlive: true,
noColor: false,
args: {}
},
e2e: {
options: {
args: {}
}
}
}
And here's the Protractor configuration file:
exports.config = {
specs: ['./suites/*.js'],
baseUrl: 'http://localhost:9000',
maxSessions: 1,
multiCapabilities: [{
browserName: 'chrome'
}],
};
How would you handle this case to let tests run on both a desktop machine, and a remote machine (such as Jenkins)?
According to this issue related on grunt-connect-proxy, this is a bug occurring when dealing with HTTPS endpoints. Use the master/ version instead.
Package.json:
"grunt-connect-proxy": "https://github.com/drewzboto/grunt-connect-proxy#master",
Gruntfile:
proxies: [{
context: '/api',
host: 'myserver.com',
port: 443,
https: true
}]

Resources