SoFunction
Updated on 2025-04-12

Detailed explanation of how to add proxyTable proxy in nuxt

background

When developing vue projects locally, when you are used to proxyTable solving local cross-domain problems and switching to nuxt, you will find that adding proxyTable settings has no effect. That is because you are using vue scaffolding to generate vue projects, which has already written relevant proxyTable settings code for you.

build/

// proxy api requests
(proxyTable).forEach(function (context) {
 var options = proxyTable[context]
 if (typeof options === 'string') {
  options = { target: options }
 }
 (proxyMiddleware( || context, options))
})

Here is the form of express middleware, and the dependency used is http-proxy-middleware

nuxt also has the concept of middleware, but this middleware is not express middleware, so how do we add it to nuxt?

How to do it

First, install dependencies

npm install --save-dev express http-proxy-middleware

Then create a file in the root directory

const { Nuxt, Builder } = require('nuxt')
const app = require('express')()
var proxyMiddleware = require('http-proxy-middleware')
var config = require('./')
// We initialize with these options:const isProd = .NODE_ENV === 'production'
const nuxt = new Nuxt({ dev: !isProd })
// The production mode does not require buildif (!isProd) {
 const builder = new Builder(nuxt)
 ()
}

// proxy api requests Here is the setting of the proxyTable intermediate price addedvar proxyTable = 
(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
   options = { target: options }
  }
  (proxyMiddleware( || context, options))
 })
()//Here is the middleware to add nuxt rendering layer service


(3000)
('Server is listening on http://localhost:3000')

Then add the following code

 = {
  dev: {
  proxyTable: {
     '/api':
      {
        target: 'http://localhost:7001', // 
        pathRewrite: { '^/api': '/' }
      }
    }
   }
}

Then the node is running.

If you feel that it is inconvenient to run, you can add the command to the file.

{
   "scripts": {
    "dev": "nuxt --port=8080",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "precommit": "npm run lint",
    "server": "node "
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.