4

I'm using the following configuration in my vue.config.js located in the root of my repository and it's not working.

  module.exports = {
    devServer: {
        proxy: "http://localhost:3030"
      }
  }

and this is how I'm trying to call it

  return await fetch("/posts", options).then((response) =>
    response.json()
  ).catch(e => console.log("Error fetching posts", e));

however when I change the calling code to the code shown below everything works

  return await fetch("http://localhost:3030/posts", options).then((response) =>
    response.json()
  ).catch(e => console.log("Error fetching posts", e));

Edit:

I should have mentioned that I'm using Vite for builds as that was causing some other problems for me with environment variables so it's possible they are causing problems with proxies too.

I looked into this more and it turns out that Vite does have proxy features and so I tried updating my code to use their proxy with still no luck.

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    "/posts": "http://localhost:3030/posts"
  }
})
2
  • proxy takes an object as the argument, where the property 'key' is a path. What are you trying to achieve here? Commented Jun 15, 2021 at 19:08
  • 1
    @match I'm wanting the call to fetch("/posts", options) to resolve to http://localhost:3030/posts in dev builds Commented Jun 15, 2021 at 20:30

1 Answer 1

9

vue.config.js is intended for Vue CLI scaffolded projects (and your config would've worked there), not for Vite projects. Vite's configuration is stored in vite.config.js.

Your Vite config value for server.proxy contains an unnecessary /posts suffix:

"/posts": "http://localhost:3030/posts"
                                ^^^^^^

The value should just be the base URL to which the original path is appended:

"/posts": "http://localhost:3030"

Example:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      '/posts': 'http://localhost:3030'
    }
  }
})

GitHub demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.