yisibell / nuxt-proxy-request

A http proxy module for nuxt(3) powered by h3-proxy.
12 stars 0 forks source link

Is is possible to intercept the headers of a request? #3

Closed TimGuendel closed 1 year ago

TimGuendel commented 1 year ago

Hello,

With http-proxy-middleware I was able to intercept headers of a request and change them before sending them in the proxy. Unfortunately, http-proxy-middleware does not work in prod mode with Nuxt 3.7.2, so I stumled upon this module here.

Can I achieve the same with nuxt-proxy-request?

👋

yisibell commented 1 year ago

Sure! Just use configureProxyRequest option:

export default defineNuxtConfig({
  modules: [
    'nuxt-proxy-request'
  ],
  proxy: {
    options: [
      {
        target: 'http://www.example.com',
        pathFilter: ['/api/**'],
        pathRewrite: {
          '^/api': ''
        },

        // the param `event` is H3Event
         configureProxyRequest: function(event) {
              // return your custom options of proxyRequest
              return {
                headers: {
                   // Add some req headers
                }
              }
         }

        }
    ]
  }

})

more details pls see h3-proxy

yisibell commented 1 year ago

Do not use any imports, in nuxt-proxy-request, the function type option is only copied from the source code.

import foo from 'foo'

{
 configureProxyRequest: function(event) {
   const someValue = foo() // Invalid, an error will be reported.
  return {
    // ...
  }
 }
}
TimGuendel commented 1 year ago

I am not sure how to implement this. This is how I used to do it. How to I conditionally add headers?

const apiProxyMiddleware = createProxyMiddleware({
    // [...]
    on: {
        proxyReq: (proxyReq, req, res) => {
            const token = getToken();
            if (token) {
                proxyReq.setHeader('token', token);
            }
        },
    }
})

🤔

yisibell commented 1 year ago

I am not sure how to implement this. This is how I used to do it. How to I conditionally add headers?

const apiProxyMiddleware = createProxyMiddleware({
    // [...]
    on: {
        proxyReq: (proxyReq, req, res) => {
            const token = getToken();
            if (token) {
                proxyReq.setHeader('token', token);
            }
        },
    }
})

🤔

// event.node.req.headers
{
 configureProxyRequest(event) {
  const headers = event.node.req.headers

  console.log(headers) //Existing `headers`

  // some logic...

  return {
    headers: {
      token: 'set here'
   }
  }
 }
}
TimGuendel commented 1 year ago

I tried that, but this error shows up:

image

yisibell commented 1 year ago

I tried that, but this error shows up:

image

Implement this part inside the configureProxyRequest function.

const token = getToken()

Due to the use of JSON.stringify, the code was only copied.

TimGuendel commented 1 year ago

I did not even call getToken(). The error happens with your example code:

configureProxyRequest(event) {
    const headers = event.node.req.headers

    console.log(headers) //Existing `headers`

    // some logic...

    return {
        headers: {
            token: 'set here'
        }
    }
}
yisibell commented 1 year ago

I did not even call getToken(). The error happens with your example code:

configureProxyRequest(event) {
    const headers = event.node.req.headers

    console.log(headers) //Existing `headers`

    // some logic...

    return {
        headers: {
            token: 'set here'
        }
    }
}

There is indeed a problem. I will fix it as soon as possible, or you can directly use h3-proxy.

TimGuendel commented 1 year ago

How do I use h3-proxy with Nuxt? I tried with a plugin, but I am getting errors with this:

nuxtApp.vueApp.use(eventHandler(proxyEventHandler));

yisibell commented 1 year ago

I tried that, but this error shows up:

image

I had fixed it in v1.7.0

{
      configureProxyRequest: function (event) { // Do not use `configureProxyRequest() {}`
          console.log(event.node.req.headers)
          return {
            headers: {
              token: 'set some token value',
            },
          }
        },
}

retry above code.

TimGuendel commented 1 year ago

With 1.7.0 I am getting this:

[nitro 09:46:08]  ERROR  RollupError: 'import' and 'export' may only appear at the top level (Note that you need plugins to import files that are not JavaScript)

 8:         const runtimeOptions = [].concat(useRuntimeConfig().proxy?.options)[0 ?? 0]
 9:
10:         export default createProxyMiddleware(defu(runtimeOptions, buildtimeOptions))
            ^
✔ Nitro built in 563 ms
yisibell commented 1 year ago

With 1.7.0 I am getting this:

[nitro 09:46:08]  ERROR  RollupError: 'import' and 'export' may only appear at the top level (Note that you need plugins to import files that are not JavaScript)

 8:         const runtimeOptions = [].concat(useRuntimeConfig().proxy?.options)[0 ?? 0]
 9:
10:         export default createProxyMiddleware(defu(runtimeOptions, buildtimeOptions))
            ^
✔ Nitro built in 563 ms

pls show me your code.

TimGuendel commented 1 year ago
    proxy: {
        options: [
            {
                target: process.env.BACKEND_URL as string,
                pathFilter: ['/api/**'],
                pathRewrite: {
                    '^/api': ''
                },
                configureProxyRequest: function (event) { // Do not use `configureProxyRequest() {}`
                    console.log(event.node.req.headers)
                    return {
                        headers: {
                            token: 'set some token value',
                        },
                    }
                },
            }
        ]
    },
yisibell commented 1 year ago
    proxy: {
        options: [
            {
                target: process.env.BACKEND_URL as string,
                pathFilter: ['/api/**'],
                pathRewrite: {
                    '^/api': ''
                },
                configureProxyRequest: function (event) { // Do not use `configureProxyRequest() {}`
                    console.log(event.node.req.headers)
                    return {
                        headers: {
                            token: 'set some token value',
                        },
                    }
                },
            }
        ]
    },

remove the Single-Line Comments // Do not use configureProxyRequest() {} .

yisibell commented 1 year ago

How do I use h3-proxy with Nuxt? I tried with a plugin, but I am getting errors with this:

nuxtApp.vueApp.use(eventHandler(proxyEventHandler));

See https://github.com/yisibell/h3-proxy#nuxt