Activities

TrueCarry

TrueCarry posted a new feature request

proxy-module •

idea Update version in npm

What problem does this feature solve?

Currently published proxy module relies on [email protected], which uses some outdated dependencies. In repository package.json already uses ^0.20.0, but after I removed @nuxtjs/axios and installed it back, I still got [email protected]

CHCP

CHCP posted a new question

proxy-module •

process.env.BASE_URL does not work in nuxt proxy module: Missing "target" option

Hello there:
I am using @nuxtjs/axios, @nuxtjs/proxy, @nuxtjs/dotenv, cross-env to implement API proxy.
1, When I use process.env.BASE URL in nuxt.config.js proxy module, it does not work, but when I use direct url it is work.
2, And process.env.BASE URL in nuxt.config.js axios module is undefined, why?

Does anyone can help me? Thank you very much.

1, Nuxt version: 2.12.2, @nuxtjs/dotenv version: 1.4.2, @nuxtjs/axios version:5.10.3, @nuxtjs/proxy version: 1.3.3
2, Config files as follows:
2.1, .env.prod:
NODE ENV=production
BASE URL=https://api.test.com

2.2 package.json:

"scripts": {
"dev": "cross-env NODE ENV=development nuxt",
"build:prod": "cross-env NODE ENV=production nuxt build",
"start": "nuxt start",
}

2.3,nuxt.config.js:
require('dotenv').config()
export default {
mode: 'universal',

buildModules: [
['@nuxtjs/dotenv', {
filename: '.env.prod',
}],
],

axios: {
baseURL: process.env.BASE URL,
proxy: true,
},
proxy: {
'/artv1/': {
target: process.env.BASE URL,
),

}

Run in server mode, commands: npm run build:prod, npm run start.
DISPLAY: FATAL [HPM] Missing "target" option. Example: {target: "http://www.example.org"}
at Object.createConfig (nodemodules\http-proxy-middleware\lib\config-factory.js:43:11) at new HttpProxyMiddleware (nodemodules\http-proxy-middleware\lib\index.js:17:30)
at module.exports (nodemodules\http-proxy-middleware\index.js:4:10) at nodemodules\@nuxtjs\proxy\lib\module.js:63:30

leo3linbeck

leo3linbeck posted a new question

proxy-module •

Axios-Proxy-CORS weirdness

I'm stumped. Here is the situation:

I'm making HTTPS calls to a CouchDB database from a Nuxt universal web app. CORS is enabled on the CouchDB server, which is running on an AWS EC2 instance. The database is accessible with Basic Authentication.

The Nuxt app is making Axios calls using @nuxtjs/axios module. No proxy is being used right now (more on this in a bit). Simple calls - basically a GET and a PUT to read and write documents to the CouchDB database. Calls are made with Authentication header and username:password encoded base64. It's a pattern I've used often without a lot of drama. All of these calls are made from Actions in the Vuex store.

However, I've always done my development on a Mac with Safari as the primary browser (it's the primary browser of my user base). Things work just fine although configuring CouchDB for both HTTPS and CORS is a little tricky. But it works, except…

,.,it doesn't work on Chrome, Firefox, or iOS Safari. Just macOS Safari. What??? That's weird, right? They appear to fail somewhat similarly; Firefox never makes it past the OPTION preflight check, and I think that's also true for Chrome but it's not so clear. In both cases the connection is simply drops with an ECONNRESET error and extreme prejudice. No response packet, just a cyberdoor slammed in my face by the CouchDB server.

Anyhoo, I thought I'd get to the bottom of what was going on by using an http sniffer. I figured there must be something with the headers, since CORS is kind of an evolving standard and Chrome has been messing around with their CORS stuff in response to security threats.

So I fired up HTTP Toolkit, and launched instances of both Chrome and Firefox and pointed them at my development instance running on localhost:3000. Lo and behold, they both worked! Nice smooth fetching of data, no drama.

What immediately came to my mind is that this must indeed be a CORS issue - the only difference with the instances of Chrome and Firefox running HTTP Toolkit an those not running it is that the http requests are being proxied. I'm sure HTTP Toolkit manages the CORS issues since otherwise it wouldn't serve its intended purpose.

So I tried setting up the @nuxtjs/proxy module to proxy my Axios calls, hoping that would solve the problem. Now I've never set up an http proxy before but I figured the documentation is so sparse because it must be easy, right? Uh, yeah.

I tried for two days and I could not get it to work. I would get an error saying that the attempt to proxy localhost:3000 to CouchDB.com:6984 was unsuccessful because of ECONNRESET. I could not get it to work, and I could not figure out how to get more information about what was happening. Keep in mind that both macOS Safari and the HTTP Toolkit instances of Chrome and Firefox were doing just fine. So it seems like it has to be something about the way the proxy was being handled - it probably needed some magical CORS headers or pixie dust or some damn thing. But I could not figure out how to get more visibility into why the connection was being dropped.

In addition, I'm not even sure this is the right track. I've read some conflicting statements around the web on this kind of stuff. For instance, can you use @nuxtjs/proxy in a universal app? Seems like you can, but I've also seen claims that you can't.

If you've made it this far, I appreciate it and will end this little discourse with the following questions:

  1. Can I use @nuxtjs/proxy in a universal app?
  2. Is there some why to get more visibility into what is happening with the proxy?
  3. Why do I need to do this? As I said above, all of these CouchDB calls are taking place in the Vuex store. Aren't those calls executed server-side? And if they're on the server, why do I need a proxy? Why is CORS even an issue?

Here's the Vuex Action that I'm calling:

getCartridge({ commit, state }) {
    if (state.cartridgeId) {
        commit('setLoading', true)
        const params = { include_docs: true }
        const config = {
            params,
            withCredentials: true,
            headers: {
                Authorization: `Basic ${auth64}`
            }
        }
        this.$axios
            .$get(`https://ceci.nest.pas.une.db.com:6984/production/${state.cartridgeId}`, { ...config })
            .then((cartridge) => {
                if (!cartridge) {
                    commit('setCartridgeResults', 'Not Found')
                } else {
                    console.log('cartridge', cartridge)
                    commit('setCartridge', cartridge)
                    switch (cartridge.status) {
                        case 'shipped':
                        case 'received':
                            commit('setLinkingStep', 2)
                            break
                        case 'linked':
                        case 'underway':
                        case 'pending':
                        case 'completed':
                        case 'cancelled':
                            commit('setCartridgeResults', 'Already Linked')
                            break
                        default:
                            commit('setCartridgeResults', 'Not Linkable')
                    }
                }
                commit('setLoading', false)
            })
            .catch((error) => {
                commit('setLoading', false)
                if (error.status === 404) {
                    commit('setCartridgeResults', 'Not Found')
                } else {
                    commit('setCartridgeResults', 'Error')
                }
            })
    }
}

This Action is called from the following computed property on the associated Page:

    cartridgeId: {
        get() {
            return this.$store.state.cartridgeId
        },
        set(cartridgeId) {
            console.log(cartridgeId)
            this.$store.commit(`setCartridgeId`, cartridgeId ? cartridgeId.toUpperCase() : '')
            if (cartridgeId) {
                if (cartridgeId.length === 24) {
                    this.$store.dispatch(`getCartridge`)
                } else if (cartridgeId.length > 24) {
                    this.$store.commit(`setCartridgeId`, cartridgeId[24])
                    this.$store.commit(`setCartridgeResults`, '')
                } else {
                    this.$store.commit(`setCartridgeResults`, '')
                }
            } else {
                this.$store.commit(`setCartridgeResults`, '')
            }
        }
    },

So, to recap: I have a universal app that successfully makes authenticated CORS calls to a CouchDB server if I use the app on macOS Safari or proxied instances of Chrome or Firefox, but fails on regular Chrome, Firefox, and iOS Safari. And I can't get @nuxtjs/proxy to work for me.

Thanks for any guidance you can provide. Cheers,

L3

msickpaler

msickpaler posted a new question

proxy-module •

target value with docker-compose

Usually, we input target value like below.

proxy: {
'/api': {
target: 'http://localhost:3001'

But i think "maybe, i can use docker container name???" like below.

proxy: {
'/api': {
target: 'backend:3001'

(sample) docker-compose.yml
services:
db:
frontend:
backend:

Does anyone know about it?
Thanks.

jansen-imagem

jansen-imagem resolved the question #c38

proxy-module •

Auth headers conflicts

For anyone facing this issue in the future. Here is my solution:

I imported axios in the test.js file. So I did not use the $axios one provided via nuxt. This way the request wont be happening through the nuxt configuration and the request will be made with auth settings provided in the proxy settings.

jansen-imagem

jansen-imagem posted a new question

proxy-module •

Auth headers conflicts

I'm having an issue with the options.auth from http-proxy in combination with an user session from the auth module from nuxt.

I created a proxy to add some auth headers that I need to send to a 3th party API Endpoint. When I send a Axios GET request to that proxy url, everything is fine. When I log in in my application and then I send a request to the API, the provided auth information in the config is overridden by the auth headers set by the auth module.

Some of my config:

nuxt.config.js

  modules: [
    "@nuxtjs/axios",
    "@nuxtjs/proxy",
    "@nuxtjs/auth",
    ...
  ],

  axios: {
    proxy: true,
  },

  proxy: {
    "/api": "http://api1.com/",
    "/api2": {
      target: "http://api2.com/",
      auth: "username:password",
    },
  },

test.js

async () => {
    const result = await this.$axios.get(`/api2/some/route`);
    console.log("result", result);
}

It looks like the headers are overridden by the nuxt auth module that are being send to the proxy endpoint. Anyone have ideas about this?

jordanleven

jordanleven posted a new question

proxy-module •

Using Proxy Module with Docker

Are there special considerations I need to take when using this module with Docker? Although I'm able to get the proxy working locally without Docker, I'm having an issue using the proxy module locally with Docker. Specifically, the route returns a 404 instead of the target.

My Nuxt config, right now, is using the example configuration from the docs.

  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://github.com/nuxt-community/dotenv-module
    '@nuxtjs/dotenv',
    '@nuxtjs/proxy',
  ],
  axios: {
    proxy: true,
  },
  proxy: {
    '/api': {
      target: 'http://example.com',
      pathRewrite: {
        '^/api' : '/'
        }
      }
  },

When hitting localhost after running nuxt, I can visit localhost/api and have it proxy to example.com. However, when building the app and using Docker, visiting localhost/api results in the 404. Notably, hitting localhost in both instances gives me the expected app apex.

mpgalaxy

mpgalaxy posted a new feature request

proxy-module •

idea Use proxy module with company proxy

What problem does this feature solve?

Currently the proxy module can't make use of a company proxy server, resulting in timeout with external identity provider(e.g. keycloak), which is being proxied through /auth. Although the docker container is configured properly for using the company proxy, nuxt.js and especially the nuxt proxy module don't utilize these settings.

What does the proposed changes look like?

Add a boolean flag as well as configuration option for nuxt.config to utilize the company proxy server, e.g.:

proxy: {
    '/auth': {
      target:
        (process.env.KEYCLOAK_SCHEME || 'http') +
        '://' +
        (process.env.KEYCLOAK_HOST || 'localhost') +
        ':' +
        (process.env.KEYCLOAK_PORT || '8080'),
      useCompanyProxy: true,
      companyProxy: process.env.COMPANY_HTTP_PROXY // example: http://companyproxy:8888
    },
...
Jamiewarb

Jamiewarb posted a new question

proxy-module •

Debug mode

I'm using the proxy module, but am getting a 404.

I can see the URL the browser is posting too, but I can't then see what URL it is being forwarded on to.

Is there any such debug mode or logging available to log what URL the request is being forwarded to, and to check the proxy is even receiving the request properly?

I had a look at https://github.com/chimurai/http-proxy-middleware, and tried to add logLevel: 'debug' to the options, like the below:

proxy: {
  '/api/': {
    target: `https://domain.com`,
    logLevel: 'debug',
  },
},

I also tried as a global option:

modules: [
  ['@nuxtjs/proxy', { logLevel: 'debug' }],
],

But I can't seem to get any logs. Would you be able to let me know how I can do this correctly please?

MikeKonan

MikeKonan posted a new bug report

proxy-module •

bug SSE events are not being forwarded in production mode

Version

1.3.3

Reproduction link

https://github.com/MikeKonan/nuxtproxysse_bug

Steps to reproduce

  1. Start express server - "node ./server/index.js"
  2. Start web app - "npm run dev" or "npm run build && npm run start"

What is expected ?

events are being shown in chrome debugger

What is actually happening?

events are NOT being shown in chrome debugger

Additional comments?

It's working as expected in develop mode - HTTP request reaches 200 and events are being shown in chrome debugger. But not working on a production mode when HTTP request succeeds with 200 but no events are being shown.

1isten

1isten posted a new question

proxy-module •

Doesn't work with Express?

I created a project with npx create-nuxt-app my-nuxt-app. In the "Choose custom server framework" section I chose Express.

For APIs I have a separated Laravel project running on http://127.0.0.1:8000/api/xxx.

Below is my nuxt.config.js config:

{
  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    proxy: true,
  },

  proxy: {
    '/api/': 'http://127.0.0.1:8000',
  },
}

Now I start the nuxt app with npm run dev on http://localhost:3000, the proxy does not work… axios still sends api requests to localhost:3000. May I know if I missed some steps or the proxy module only works with nuxt default server?

Kerita

Kerita posted a new question

proxy-module •

How to get the client ip ?

My app is using proxy module. When the browser sends a request to the server, how can the server know the browser ip?

SHxKM

SHxKM posted a new question

proxy-module •

How does this module prevent CORS?

I'm asking this after writing this question on the django-cors-headers repo. I was wondering why I didn't have to deal with CORS/preflighted requests with Nuxt's axios module, and then I read this in Nuxt's documentation:

proxy

Default: false

You can easily integrate Axios with Proxy Module and is much recommended to prevent CORS and deployment problems.

Why and how does the proxy module "prevent" CORS related problems? I have proxy enabled and probably that's the reason why I'm not getting CORS errors.

carlmjohnson

carlmjohnson posted a new feature request

proxy-module •

idea Add ability to use context matching function

What problem does this feature solve?

The following example is in the README for http-proxy-middleware, but AFAICT, cannot be implemented in proxy-module:

var filter = function(pathname, req) {
  return pathname.match('^/api') && req.method === 'GET';
};

var apiProxy = proxy(filter, { target: 'http://www.example.org' });

I would like the ability to use context matching functions.

What does the proposed changes look like?

On a user level it might look like:

  proxy: {
    [(pathname, req) => pathname.match('^/api') && req.method === 'GET']: { target: 'http://www.example.org' }
  },
sowinski

sowinski posted a new question

proxy-module •

Dynamic proxy target url

Hi,
I use the proxy feature and it is working well.
proxy: {
'/rest': process.env.PROXY_URL || 'https://www.example.com',
},

But I have 47 domains and I would like to change them with a middleware or plugin the proxy URL dynamically on each request.

Is this possible?

Example: If someone is entering the website from
www.example.com => then the proxy should be going to www.example.com
www.example.it => then the proxy should be going to www.example.it

Dok11

Dok11 posted a new question

proxy-module •

How use proxy? Please, provide example

I write:

export default {
  modules: [
    ['@nuxtjs/proxy', {
      proxy: {
        '/f': 'http://my-domain/'
      }
    }]
  ]
}

and it is not works. Is I do right? Maybe proxy must be place in another part of config?

zajca

zajca resolved the question #c27

proxy-module •

Proxy behind proxy

find out that on ssr request was called to http://proxy:port/http://localhost:10000 where is app which throws 502 since localhost can't be used with this proxy and it's whitelisted. Interesting is that this happened only in SSR. And my host for app is not localhost but 127.0.0.1.
I have to add to .env http_proxy="" to force ignore proxy.
It looks to me that on ssr no_proxy env var is no readed or something. :/

zajca

zajca posted a new question

proxy-module •

Proxy behind proxy

I now it sounds weird, but on my production server app si behind corporate proxy. Api is on same server and it's accessible on localhost:8080 so it doesnt have to use corporate proxy.

No the weird thing.

When I navigate in browser to page with asyncData request is going to nuxt proxy and it's success. But when I refresh page and asyncData are called in SSR proxy will return 502. Which is like super weird I don't get why is there a difference.

renestalder

renestalder posted a new question

proxy-module •

How to handle proxy with Nuxt serverMiddleware in between

I use a serverMiddleware to set the request body for proper server-side POST form handling. I found out via http-proxy-middleware repo that things like body-parsers will break the proxy if they run before it and the solution is to run the middleware after the proxy call.

Now, I'm not really sure how I would be able to change this in Nuxt.

That's my serverMiddleware:

import {IncomingMessage, ServerResponse} from 'http';
import {parse} from 'querystring';

export default function(req: IncomingMessage, res: ServerResponse, next: () => void) {
  let body = '';

  req.on('data', data => {
    body += data;
  });

  req.on('end', () => {
    (req as any).body = parse(body) || {};
    next();
  });
}

Removing this from my nuxt.config makes the proxy working. Otherwise the proxy answers with timeout errors or other stuff.

So I would require to run my serverMiddleware after the proxy.

Is that somehow possible?

ps. one cannot create a bug report on cmty for that module as the version list is empty but a required field.

warheartvik

warheartvik posted a new question

proxy-module •

https as target

I'm using proxy module https://axios.nuxtjs.org/options#proxy. So, If I set target with https like

proxy: {
'/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''} }
}

Should work just fine? Because I did that on my app. And the request failed with error 500

Does that means that target can't be set as https? The target work as http, but I set it as https fails

unknown.png