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.
Related
I'm following this tutorial to make my React app (localhost:3000) communicate with Node server (localhost:5000) .. so instead of typing <Link to='localhost:5000/auth/google'>Login with Google</Link> I only want it to be just '/auth/google', but when I click on the button with Link tag it sends this error "No routes matched location "/auth/google"
I'm using React v17.0.2
this is what's inside my setupProxy.js file
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
["/auth/google", /api/*],
createProxyMiddleware({
target: "http://localhost:5000",
changeOrigin: true,
})
);
};
the weird thing though is that I got no error when I type the route directly in the browser (both ports work just fine) and it redirect me to the page I want (handled by Express)
If there's no solution for this problem for now, is there any other way to use a proxy in a MERN application because from what I know adding "proxy" in package.json is not working anymore
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.
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!
This is a personal portfolio page that I'm implementing a contact form within, using nodemailer.
The nodemailer thing is all set from server side. I just need some advice on pointing the client post request to the right place in regards to development and deployment.
I figured as much for setting an environment variable for production vs development and hitting the fetch based upon that. Now I'm just wondering how to go about finding whatever I would put in the fetch for production.
would it be just pointing back into my own app:
fetch(www.mydomain.com/send-email, data) ...
I'm in the Heroku docs trying to figure this out.
Basically, I have a huge blind spot which is hitting a server API from Create React App that isn't launched independently on localhost:3000. I have yet to hit a server route from my client that wasn't served locally on localhost. When I push this to Heroku, I need to have the right route or config, what I need is some advice on how to do this.
I understand proxying somewhat. Just wondering what the steps are to properly hit my server route from an client/server deployed on Heroku as opposed to localhost:3000 during deployment.
When I'm in development I pretty much always axios.post a server that I've spun up on localhost:3000,
which I then hit with something like this coming from my client..
axios.post('localhost:3000/send-email', data)
.then( () => {
setSent(true)
})
.then(() => {
resetForm()
})
.catch((err)=> {
console.log('Message not sent', err)
})
}
...which is then handled by an endpoint on the express server listening on localhost:3000, that looks somewhat like what I've pasted below.
const express =
require('express'),
bodyParser = require('body-parser'),
nodemailer = require('nodemailer'),
cors = require('cors'), path = require('path'),
port = process.env.PORT || 3000, publicPath = path.join(__dirname, '..', 'build');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.static(publicPath));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.post('/send-email', (req, res) => {
console.log('request: ', req.body)
let data = req.body;
let transporter = nodemailer.createTransport({
service: 'gmail',
port: 465,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
let mailOptions = {
from: data.email,
to: process.env.EMAIL,
subject: `${data.subject}`,
html: `<p>${data.name}</p>
<p>${data.email}</p>
<p>${data.message}</p>`
};
transporter.sendMail(mailOptions,
(err, res) => {
if(err) {
res.send(err)
} else {
res.send('Success')
}
transporter.close();
});
})
app.listen(port, () => {
console.log(`Server is up on port ${port}!`);
});
folder structure is like this:
main
|-server
|-server.js
|-src
|-components
|-Contact.js
Use the process.env.NODE_ENV variable to differ the environments.
When you run npm start, it is always equal to 'development', when you run npm test it is always equal to 'test', and when you run npm run build to make a production bundle, it is always equal to 'production'. You cannot override NODE_ENV manually.
Therefore, you can create and export a function like
export function apiDomain() {
const production = process.env.NODE_ENV === 'production'
return production ? 'anotherDoman' : 'localhost:3000'
}
or maybe, depending on your requirements
export function apiDomain() {
const { protocol, hostname, origin } = window.location
return hostname === 'localhost' ? `${protocol}//${hostname}` : origin
}
For more details, take a look at https://create-react-app.dev/docs/adding-custom-environment-variables/
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