Configuring a devServer proxy leads to a 404 error

Within my src/vue.config.js file, I have the following configuration:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        changeOrigin: true,
      },
    },
  },
};

When I call the API using the following axios request:

axios.get('/api/parts')
    .then(result => commit('updateParts', result.data))
    .catch(console.error);

However, instead of receiving the expected data, I continue to encounter the following error message:

Error: "Request failed with status code 404"

Upon further investigation, I noticed that the request is being directed to port 8080 instead of 8081. Interestingly, I can access the API without any issues through a web browser.

How should I go about debugging this issue?

Answer №1

It appears that your vue.config.js file is mistakenly placed in the src folder instead of being located at the root of your project. To resolve this issue, simply move the file to the correct directory.

If you need further guidance on configuring the server, you can refer to the documentation provided here: https://cli.vuejs.org/config/#devserver-proxy. It seems like you are following the correct steps, but the file is just misplaced in the wrong folder.

Answer №2

After testing several different combinations, I finally found the solution to my problem.

In my setup, I am utilizing Axios and my application is currently hosted on port 8080

Main JavaScript file:

axios.defaults.baseURL = 'http://localhost:8080/api/'

Vue configuration file:

module.exports = {
    devServer: {
      proxy: 'https://reqres.in'
    }
}

Vue Component Code:

this.axios.get("users")
   .then(response => {
    this.items = response.data.data;
    this.isLoading = false;
})

Network Activity in Browser:

https://example.com/network_tab.png

Answer №3

Using a proxy can cause issues if the remote address does not match the request URL and port. To fix this in your vue.config.js, make the following edits:

proxy: {
          '/api': {
              target: 'http://localhost:8080',
              changeOrigin: true
          }

Alternatively, you can utilize the rewrite attribute like so:

proxy: {
          '/api': {
              target: 'http://localhost:8080',
              changeOrigin: true,
              pathRewrite: { '^/api': '/'}
          }
      }

The difference lies in the actual request made - the top option will be http://localhost:8080/api/..., while the rewrite option will be http://localhost:8080/...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop displaying AJAX requests in the console tab of Firebug, similar to how Twitter does it

I'm looking for a way to prevent my AJAX calls from being logged in Firebug's Console tab, similar to how Twitter does it. When using Twitter search, you'll see a live update feed showing "5 tweets since you searched." Twitter sends periodic ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

What is the best way to set up http-server with history mode in Vue JS 2?

I've encountered an issue with my Vue JS application that is built in the dist directory. To run it, I'm using http-server, which I installed globally using the command: npm install -g http-server The app runs successfully when I use the command ...

Trigger a Vue method using jQuery when a click event occurs

I'm attempting to attach a click event to an existing DOM element. <div class="logMe" data-log-id="{{ data.log }}"></div> ... <div id="events"></div> Struggling to access external Vue methods within my jQuery click handler. A ...

The HitBTC API in PHP encountered a problem when attempting to process the request to access the trading balance at /api/2/trading/balance. The error

My current code is not functioning as expected. I am attempting to display the account balance, and have been using var_dump($curl_response) to track where the code is failing. When I dump the final result, it returns null. <?php $headers = array ( ...

A function that handles HTTP request and response

In order to decrypt data, I need to retrieve the encrypted response by hitting a specific URL and then use that encrypted data along with a key to decrypt it. Initially, I attempted to fetch the data response using POSTMAN, but all I got back was a series ...

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

How can an HTML5 application be configured to enable access to intranet and local files?

It's a known fact that accessing the local path of a file added using a file input field or drag-and-drop is not possible even with the new FileAPI. Whether this limitation is good, bad, or ugly is not up for debate. The FileAPI specs clearly state th ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

PageCallbacks in .NET 1.1

Is it possible to utilize PageMethods in .NET 1.1 for making server-side method calls from the client side? Could you provide a brief explanation on how to use this feature by calling PageMethods.MyMethod(); ? ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Retrieving the current date in React from a distinct date format

Does anyone know how to retrieve today's date in the following format using React? "2019020420" I have a function that currently retrieves the current date. How can I modify it to output the desired date format shown above? getCurrentDate( ...

Steps for recreating a Jquery Mobile form element with the same name after destroying it

As I delve into Jquery Mobile, I encounter a scenario where I must dynamically generate form fields (select, input, etc) using the following approach: $fieldInput = $('<input type="text" name="' + fieldName + '" />'); Initially, ...

Warning: Potential critical dependency detected while utilizing react-pdf package

When attempting to showcase a PDF on my react application, I encountered the following warning: /node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js Critical dependency: require function is used in a way in which dependencies cannot be static ...

Remove leading spaces before text

Is there a way to remove spaces before text only? " with spaces between" What I want: "some text with spaces between" I have tried using text.replace(/\s/g, '') but it doesn't give the desired result: "sometextwithspacesbe ...

Is it possible to use cakephp and AJAX to determine if a table is empty?

Is there a way to determine if a table is empty using CakePHP and AJAX? In my index.ctp, I have included an image that, when clicked, will notify the user about the status of the table. If the table is empty, an alert box will pop up; otherwise, the user w ...

A method for determining the quantity of <li> elements within a <ul> container while applying specific conditions

I am currently using document.querySelectorAll('ul > li').length to count the total number of items in my list. However, I am wondering if there is a way to count only those items that meet a specific condition. For example: <ul> < ...

Generate a key pair using the cryto library and then use it with the json

There's a new method called generateKeyPair in node 10, and I am utilizing it in the following way: const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 4096, publicKeyEncoding: { type: "spki", format: "pem ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...