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

Dealing with a mysterious Vuejs object that remains undefined within a watched property

Encountering an issue with Vue.js's watched property. Despite the list being defined, I am receiving the error: Cannot read property 'list' of undefined. This occurs after the if check at the line var index ..... watch: { selectedRole: () ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

My React higher order component implementation is revealing the protected route momentarily

import { useRouter } from "next/router"; import { useEffect } from "react"; import axios from "axios"; export default (ChildComponent) => { const enhanceComponent = (props) => { const router = useRouter(); co ...

Is there a way for me to incorporate view charts into my JavaScript file with Vue.js?

I have a project with index.html, script.js, and style.js. I want to implement vue-echarts for a single page. How can I achieve this? <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Clicking on the button will result in the addition of new

Having some trouble with jQuery as I try to dynamically add and remove HTML elements (on click of +) while also making sure each element has a unique name and ID like "name_1", "name_2"... Unfortunately, things aren't quite going as planned. Below i ...

Using Javascript to multiply strings

While working on the leetcode problem related to multiplication, I encountered an interesting issue. Given two non-negative integers num1 and num2 represented as strings, the task is to return the product of these two numbers, also in string form. However ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

At what point does the promise's then function transition to being either fulfilled or rejected?

When dealing with promises in JavaScript, the then() method returns a promise that can be in one of three states: pending, fulfilled, or rejected. You can create a promise using the resolved and rejected methods to indicate when it should be fulfilled or r ...

Adding JSON data to an array in Angular JS using the push method

I am encountering difficulties with adding data to an existing array. Currently, I have set up a table to display the data, but I want to also include the data in the table when a user enters an 8-digit barcode. Factory angular.module('app.pickU ...

What are some ways to change the appearance of a component using its parent?

In order to make changes to the CSS properties of a Vue component from its parent, effectively overriding any existing styles within the component, I am seeking a solution. Initially, I assumed that styling a component like <my-component> directly f ...

What initiates Electron after npm processes the package.json file?

As I delve into the realms of JavaScript, HTML, and Electron, a particular question has been playing on my mind - what exactly happens when you run electron . in the "scripts" -> "start" section of package.json? The mysterious way it operates sends shivers ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Issues encountered while retrieving data from an API using get method in Vue.js and express.js

This marks my debut question on this platform. For a school project, I have devised my own API with a limited number of routes: The designated routes app.get('/AREA/', (req, res) => res.status(200).send({ message: 'Welcome to the A ...

Angular directive ng-template serves as a component type

In the code snippet below, <!DOCTYPE html> <html> <head> ..... </head> <body ng-app="app"> <script type="text/ng-template" id="my-info-msg.html"> <s ...

Player-Oriented Online Game: Addressing Target Accuracy Challenges in ctx.setTransform

I'm currently developing a web game and my goal is to ensure that the player remains at the center of the screen. However, as the player moves further away from the center, the accuracy decreases. I've attempted using ctx.setTransform, which work ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Exploring the process of transforming a dynamic PDF into a static PDF using PHP or NodeJS

Issue I am looking for a PHP/NodeJS API that can convert editable PDF files to non-editable PDFs online. Our client application requires the user to download PDF files that cannot be modified using software like Foxit Reader or Adobe. We are currently us ...

Guide on making a personalized object in JavaScript

I am struggling with a piece of JavaScript code that looks like this: var myData=[]; $.getJSON( path_url , function(data){ var len = data.rows.length; for (var i = 0; i < len; i++){ var code = data.rows[i].codeid; var ...