react app browser proxy with http-proxy-middleware - javascript

I've got problem with proxy in react app.
Target: I've got two react apps, first app is on localhost:3000 and second on localhost:3001. What I want? => When in first app I'll click on:
<a href="/app2">
<button>Second App Open</button>
</a>
Then url will change from localhost:3000 into localhost:3000/app2 and second react app show what has got in url localhost:3001.
I imported http-proxy-middleware library and create in src direction file setupProxy.js and inside:
const {createProxyMiddleware} = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
};
Anyone could help me with this?
Also I tried this code in setupProxy.js:
const express = require('express')
const {createProxyMiddleware} = require("http-proxy-middleware");
app = express()
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
But then I've received error that require(...) is not a function oraz that express is not a function, when I take express into {} then also occurs error.

I know it's late and I came across the same issue. Keeping what worked for me so that others can give it a try.This code is tested for react app created with create-react-app.
I proxied this endpoint - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(createProxyMiddleware('/api2', {
target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
changeOrigin: true,
pathRewrite: { '^/api2': '' }
})
);
}
Your .js file
triggerCORSCall() {
axios.get(`/api2/Customers?$format=json`)
.then(response => {
alert('Success');
}).catch(error => {
alert('Failure');
console.log(error);
})
}

Related

Why is vue failing to set my proxy for api routes?

I have a vue app I'm trying to connect to a flask api, all running on different ports on the same machine. My vue.config.js looks like this:
module.exports = {
// options...
devServer: {
public: 'localhost',
disableHostCheck: true,
proxy: {
'^/flask': {
target: 'http://localhost:8001',
pathRewrite: {'^/flask': '/'},
changeOrigin: true,
logLevel: "debug",
},
'/V2': {
target: 'http://localhost:8001',
changeOrigin: true,
pathRewrite: {'^/V2': ''}
},
}
}
}
where port 8001 is the port the flask is running on. Except the actual api requests from vue are being sent to port 9600 (and failing). For example:
fetchData() {
const path = '/flask/search';
console.log('Homepage recieved query')
if (this.queryform !== 'initVal') {
axios.post(path, this.queryform)
.then((res) => {
this.queryResult = res.data;
console.log('Homepage recieved results');
})
.catch((error) => {
console.log(error);
});
}
},
results in the error "Proxy error: Could not proxy request //search from ****:8002 to http://localhost:9600 (ECONNREFUSED)." *** is the ip address, omitting for privacy sake.
I know this an error within vue, I'm able to successfully use all the api routes on the flask app using my api testing program.
I can't find anywhere in the code where requests are sent to :9600, is there another configuration file I need to change?

Next.js Express Custom Server { dev: true } loads forever (empty response) but production { dev: false } works

I am using a express custom server with next.js. Custom Server
I added the next app to my router under the path /custom/uibackend/next
const next = require('next')
const app = next({ dev: true, dir: './', conf: { } })
const handle = app.getRequestHandler()
module.exports = router => {
router.all('*', (req, res) => handle(req, res))
}
If i run my app and access the route in the browser it loads for a while and gives a empty response back.
There is just this one log i the console:
info - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
If i build the app and set dev to false it works as expected and i can access the route and the pages.
const app = next({ dev: false, dir: './', conf: { } })
I used the following next.config.js file:
module.exports = {
basePath: '/custom/uibackend/next'
}
My /pages folder is in the root.
Thank you.
I have found the error.
I forgot to call app.prepare()
app.prepare().then(() => {
// add handle to router/app after app.prepare has finished
})

Express/node cookie connect.sid missing on client in production (Heroku) although visible on localhost

I have a React App that is deployed on Netlify and a GraphQL/express backend deployed on Heroku.
I use the connect.sid cookie to the server to persist login and handle other backend requests e.g. stripe payments. The cookie is generated in my local development environment; however, in production (server + postgres db deployed on Heroku + client deployed on Netlify) the connect.sid cookie is not sent back to the client.
However, when viewing the Heroku logs, I can tell that the cookie is being generated. It is just not usable or visible by the client.
Here is my node server:
const startServer = async () => {
if (typeOrmOptions.url) {
await createConnection(typeOrmOptions); // --> was this before
} else {
await createConnection(); // --> was this before
}
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }: any) => ({ req }),
introspection: true,
playground: true
});
const app = express();
const forceSsl = function(req, res, next) {
if (req.headers["x-forwarded-proto"] !== "https") {
return res.redirect(["https://", req.get("Host"), req.url].join(""));
}
return next();
};
app.use(forceSsl);
app.set("trust proxy", 1);
app.use(
session({
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 86400000,
domain
},
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
secret: "keyboard cat"
})
);
server.applyMiddleware({
app,
cors: {
origin: webUrl,
credentials: true
}
});
app.listen({ port: port }, () =>
console.log(
`🚀 Server ready at http://localhost:${port}${server.graphqlPath}, weburl = ${webUrl}`
)
);
};
startServer();
Here is the React client
const serverUrl =
process.env.NODE_ENV === "development"
? "http://localhost:4000"
: "https://server-domain.com";
const client = new ApolloClient({
uri: `${serverUrl}/graphql`,
credentials: "include"
});
function App() {
console.log(serverUrl, "uri");
return (
<ApolloProvider client={client}>
<ThemeProvider theme={theme}>
<Routes/>
</ThemeProvider>
</ApolloProvider>
);
}
export default App;
Output of the Network on localhost
Output of the cookie on localhost
Output of the Network in production
Output of the cookie (or lack thereof) in production
Output of the console in production
Output of the Heroku logging
As you can see, the sessions are being logged server side ... they just aren't making it to the client.
Banging my head against the wall -- would appreciate any help!
Any suggestions on how to fix this?

Unable to access ExpressJS endpoints NuxtJS app

I am fairly new to Nuxt and Vue. I have worked with React and Express before but I'm not sure if I'm missing a step specific to the Nuxt configuration.
I'm trying to GET data from an endpoint on my Express server, and it's working fine locally, but once I've deployed it, I'm having one of a couple of different errors. At first I was getting
Access to XMLHttpRequest at 'http://localhost:3000/ENDPOINT' from
origin 'https://APPNAME.herokuapp.com' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.
I was able to get past this by installing the cors and #nuxtjs/proxy npm packages, adding app.use(cors()) to my server and adding a changeOrigin property to proxy in nuxt.config.js.. Now I'm getting a 404 when it tries to GET APPNAME.herokuapp.com/ENDPOINT.
I created a new test app using npx create-nuxt-app, choosing express as the custom server framework and setting up a test endpoint in server/index.js
app.get('/test', (req, res) => {
res.status(200).send('reached test')
})
In my nuxt view, I added a method:
runTest () {
this.$axios.$get('/test')
.then(success => console.log('success text:', success))
}
Again, this runs fine locally, but once deployed, I got the CORS issue until I added the cors package and changeOrder. Now getting the 404, it seems like I can't access my server's endpoints. Does anyone know anything about this?
Thanks in advance for any help!
UPDATE:
My nuxt.config.js file:
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
titleTemplate: '%s - ' + process.env.npm_package_name,
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [
],
/*
** Plugins to load before mounting the App
*/
plugins: [
],
/*
** Nuxt.js dev-modules
*/
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
'#nuxtjs/eslint-module',
'#nuxtjs/vuetify'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
proxy: {
'/api/': {
target: 'http://localhost:3000/',
pathRewrite: {
'^/api/': ''
},
changeOrigin: true
}
},
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
},
/*
** vuetify module configuration
** https://github.com/nuxt-community/vuetify-module
*/
vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
dark: true,
themes: {}
}
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend (config, ctx) {
}
}
}
My server file:
const express = require('express')
const consola = require('consola')
const cors = require('cors')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
app.use(cors())
app.get('/test', (req, res) => {
res.status(200).send('reached test')
})
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
This is mostly default nuxt scaffolding on my test app.
Thanks

Node http-proxy not working behind proxy

I am using the http-proxy-middleware module, which is an express middleware. the middleware module relies on http-proxy. The node host is running behind a proxy.
I want to forward certain routes to a different service (for test purposes let's assume httpbin.org). So I defined the proxy as follows.
var proxy = require('http-proxy-middleware');
var aeProxy = proxy({
target: 'http://httpbin.org',
changeOrigin: true,
pathRewrite: {
'^/api/ae':'/get'
}
});
app.use('/api/ae', proxy);
I have also set the respective env variables (from debugging console):
process.env.HTTP_PROXY
> "http://proxy:8080"
process.env.HTTPS_PROXY
> "http://proxy:8080"
Unfortunately I only get timeouts. When running the node script in an environment without a proxy it works as expected.
Is my configuration wrong?
Credit to chimurai for this on how to connect via a corporate proxy via the agent field.
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = require("http-proxy-middleware");
// corporate proxy to connect to via environment variables
var proxyServer = process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;
var options = {
target: 'http://localhost:3000',//Proxy url
agent: new HttpsProxyAgent(proxyServer)//The actual corporate proxy sever
};
var apiProxy = proxy('/api', options);
If you are behind a V2Ray protocol, you can just set the listening address and port of your connection like bellow and you'r good to go.
var HttpsProxyAgent = require('https-proxy-agent');
const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: process.env.REACT_APP_API_URL
changeOrigin: true,
secure: false,
logLevel: "debug",
onProxyReq: fixRequestBody,
agent: new HttpsProxyAgent('http://127.0.0.1:1087'),
headers: {
'X-Auth-Token': process.env.REACT_APP_API_TOKEN
},
pathRewrite: {
'^/api': ''
}
})
);
};

Categories