Vue-resource and http-proxy-middleware not routing to backend - proxy

I am new to Vue js and writing a front end for a simple task tracker app. I am trying to use vue-resource and http-proxy-middleware to have the app connect to my backend. Backend is on port 3000, and the Vue js front end is on port 8080.
I used the proxy set up described on the Vue docs.
The method:
saveTask() {
this.$http.get('/api', {title: this.taskTitle})
.then(response => {
console.log("success");
}, response => {
console.log("error");
});
}
My Proxy Table: (in config.index.js under dev)
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
When I start up the server I see:
[HPM] Proxy created: /api -> http://localhost:3000
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...
On the request:
GET http://localhost:8080/api 404 (Not Found)
So it looks like the proxy is not working. Any help greatly appreciated.

Your setup looks good and the requests should look like they're coming from 8080 since it is a proxy.
Are you sure something should be returning where you're looking? I have literally the same setup and it works.
My guess is since http://localhost:8080/api can't be found either can http://localhost:3000 since they're the same thing.
If that doesn't solve your problem you can dig a little deeper and debug and see if anything looks funny there.
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
logLevel: 'debug',
pathRewrite: {
'^/api': '',
},
},
},
Here goes a shot of everything working with my stuff:

what worked for me was setting up a vue.config.js file on the root dir of the vue project (that is at the same level that pacakge.json) and within that file I used this code:
module.exports = {
devServer: {
proxy: {
"^/api": {
target: "http://localhost:3000",
ws: true,
changeOrigin: true
}
}
}
}
now that the proxy was setup in the vue app the request would reach my express server :D

Related

Graphql subscription in playground during local development throwing "Could not connect to websocket endpoint" in basic nestjs project

This is happening on a simple project during local development, so cloud infrastructure isn't an issue.
This is also happening in the application playground.
My module registration:
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
imports: [YeoConfigModule],
useFactory: (configService: YeoConfigService<AppConfig>) => {
const config: ApolloDriverConfig = {
debug: true,
subscriptions: {
'graphql-ws': true,
},
playground: true,
autoSchemaFile: './apps/event-service/schema.gql',
sortSchema: true,
context: ({ req, res }) => ({ req, res }),
};
const origins = configService.get('CORS_ORIGINS')();
config.cors = { origin: origins, credentials: true };
// config.path = '/apis/event-service/graphql';
return config;
},
inject: [YeoConfigService],
My app startup:
async function bootstrap(): Promise<void> {
const app = await getApp();
await app.listen(process.env.PORT ?? 3600);
}
bootstrap();
My versions:
"graphql-ws": "5.11.2",
"graphql-redis-subscriptions": "2.5.0"
"#apollo/gateway": "2.1.3",
"#nestjs/graphql": "10.1.3",
"graphql": "16.5.0",
Result:
{
"error": "Could not connect to websocket endpoint ws://localhost:3600/graphql. Please check if the endpoint url is correct."
}
Any ideas why this isn't working as expected? I've been reading the nestjs docs up at https://docs.nestjs.com/graphql/subscriptions but there's nothing that I can find about extra setup required other than adding
subscriptions: {
'graphql-ws': true,
},
when registering the graphql module.
For anyone else stumbling upon this, I have started using altair which allows me to specify the ws endpoint as well as the type of connection, among which there is a graphql-ws option.
So I went with it.
If anyone knows how to achieve this using the playground referred in the original answer, happy to mark that one as the right answer over my own.

Svelte Proxy with rollup?

I'm trying to proxy requests from a Svelte app to a different port, where my backend API runs. I want to use a rollup proxy in the dev environment.
I read the alternative of using a webpack proxy here, but I want to give rollup proxy a try.
This is not an issue in production.
As suggested, I tried configuring rollup-plugin-dev However, whenever I make a request to weatherforecast I still get an CORS error. Below is my configuration and the call:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
dev({
proxy: [{ from: '/weatherforecast', to: 'https://localhost:7262' }]
}),
// other code
];
and App.svelte looks like this:
<script>
import { onMount } from "svelte";
const endpoint = "/weatherforecast";
onMount(async function () {
try {
const response = await fetch(endpoint);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
});
</script>
Any help in solving this issue is appreciated.
What's happening is the proxy is passing through the CORS headers un-touched, so you're basically interacting with the API as though the proxy wasn't even there, with respect to CORS.
I'll note that you can get around this in dev, but keep in mind this problem will come up in production too, so you may just need to rethink how you're getting this data.
For development though, you can use something like cors-anywhere. This is a middleware that you can run through your dev server that can rewrite the headers for you.
To configure rollup-proxy on dev environment, you need to remove the call to the serve method, call the dev method and move the proxy calls inside the dev method:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
// other code
commonjs(),
// enable the rollup-plugin-dev proxy
// call `npm run start` to start the server
// still supports hot reloading
!production && dev({
dirs: ['public'],
spa: 'public/index.html',
port: 5000,
proxy: [
{ from: '/weatherforecast', to: 'https://localhost:7262/weatherforecast' },
],
}),
// line below is no longer required
// !production && serve(),
// other code
];

Nuxt Proxy changes POST to GET when proxy is set to true

In my universal nuxt app, I have setted proxy at true and rewritte my url to avoid CORS issue.
But when I'm setting proxy to true, all my post requests are changed to get request. Don't understand why and how to configure it no to have this transformation.
Here is my nuxt.config.js :
/*
** Axios module configuration
*/
axios: {
proxy: true
},
proxy: {
'/apicore/': { target: 'http://blablabla.fr', pathRewrite: { '^/apicore/': '' }, changeOrigin: true }
}
My call:
async createJoueur({ state, dispatch, commit }, data) {
const URL = '/apicore/joueur'
await this.$axios
.post(
URL,
data, {
headers: {
'Content-Type': 'application/json'
}
}
)
.then((response) => {
console.log('JOUEUR LOGGED : ')
if (response.status === 200) {
} else {
console.log('Login failed / Not found')
}
}
)
.catch((error) => {
console.log('ERROR')
})
With this proxy set to true, my post-call becomes a get one.
Do I have forgotten something in my configuration?
Thanks for your help.
I was with the same problem! i solved it using changeOrigin: false.
I know that it must be the default value (Look at changeOrigin session ),
but it seems like in nuxtjs proxy implementation this value default is true (Look at Options session) .
I had the same issue and after some logging using the onProxyReq option I found out that the issue was the Cloudflare proxy, not the nuxt proxy. Cloudflare was forwarding HTTPS requests to HTTP and this forces POST requests to become GET requests as is common with 301/302 redirects.
As far as I know, it's not possible to configure Cloudflare to do 308 redirects, which would not alter the HTTP method/body.

Ajax With ReactJS to NodeJS

I'm using webpack-dev-server while developing in ReactJS.
I also want to add a backend which will be written in NodeJS.
When I run the webpack-dev-server it binds to port 8080.
When I run node, it can't bind to the same port.
Therefore, I'm unable to perform $.ajax requests due to the SOP.
How do I get over this issue?
NodeJS:
const express = require('express');
const app = express();
app.get('/messages', function(req, res){
res.send('hello world!');
});
let server = app.listen(8081, function() {
const host = server.address().address;
const port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});
React/JS/Ajax:
$.getJSON('/messages', function(data) {
this.setState({
messages: data
});
}.bind(this));
And I'm running webpack-dev-server without any parameters.
the port of app is different from the portof your server. if you want to keep save port, you can try to use webpack proxy
module.exports = {
// the other config of your webpack
devServer: {
hot: true,
historyApiFallBack: true,
proxy: {
'/message': {
target: 'http://localhost:8081',
secure: false,
changeOrigin: true
},
},
},
}
when you fetch http://localhost:8080/messages, webpack-dev-server will proxy to http://localhost:8080/messages.
Your app is on port 8080.
Your server is on 8081.
If you want to request from the server, you need to specify the port to the server. If not, it will request to the port your app is running to, which is 8080.
$.getJSON('https://localhost:8081/messages', function(data) {
this.setState({
messages: data
});
}.bind(this));

Reverse proxy Ghost (Heroku app) from another app (expressjs)

Simple case: I have app1 - which is an install of ghost (site-blog.herokuapp.com). I have app2, which is a custom express.js app (site.herokuapp.com).
I want to serve the blog from site.herokuapp.com/blog.
For Ghost, here's part of my config.js
production: {
url: process.env.BLOG_IDENTIFIER_URL,
fileStorage: false,
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
debug: false
},
server: {
host: '0.0.0.0',
port: process.env.PORT
}
},
BLOG_IDENTIFIER_URL is set to site.herokuapp.com/blog.
For the express.js app, I have the following routing (for /blog):
router.all('*', function(req, res) {
// blog page is actually a ghost!
var blog_url = 'http://localhost:2368';
if (process.env.NODE_ENV === 'production') {
blog_url = 'http://site-blog.herokuapp.com';
}
req.headers.host = blog_url;
require('http-proxy').createProxyServer().web(req, res, { target: blog_url });
});
This works absolutely fine locally, but when I push both the repos to heroku, and try to visit site.herokuapp.com/blog, I get just a blank page and nothing in the logs. The request fails though:
I have tried a lot of stuff, both from SO and from the rest of the visible internet. Nothing seems to work. I'm stuck here for the last 4 hours. If you have anything that might help, please please leave a comment or an answer.

Resources