What could be causing API requests to be directed to the incorrect URL in Vue.js 2?

I've been experimenting with learning Vue.js 2 and routing, and I'm puzzled by a specific issue. Whenever I navigate to routes other than the home ('/') route, the localhost URL is somehow added to the API calls. Here's an example of what happens:

const url = `'https://www.reddit.com/r/'${ this.sub }/.json?limit=10'`; // this.sub represents the subreddit string

This results in a URL like:

'http://localhost:5000/subreddits/politics/https://www.reddit.com/r/politics/.json?limit=10'

Here is the code snippet causing the problem:

<script>
    export default {
        data() {
            return {
                sub: this.$route.params.sub,
                posts: [],
            }
        },
        watch: {
            '$route'(to, from) {
                this.sub = to.params.sub;
            }
        },
        methods: {
          fetchPosts: async function () {
            const url = `'https://www.reddit.com/r/'${ this.sub }/.json?limit=10'`;
            try {
              const res = await (await fetch(url)).json();
              this.posts = await (res.data.children);
            } catch(err) {
              console.error(err);
            }
          }
        },
        mounted() {
          this.fetchPosts();
        },
    }
</script>

Answer №1

There are a couple of issues in your current project setup:
1. Sending requests to the reddit host from localhost is not allowed.
2. Using backticks instead of single quotes is recommended for better code clarity.

If you utilized VUE-CLI to initialize the project, follow these two steps to address the problems:

  1. In the /config/index.js file, locate the proxyTable section and include the following configuration:
proxyTable: {
    '/reddit': {
        target: 'https://www.reddit.com/r',
        changeOrigin: true,
        pathRewrite: {
            '^/reddit': ''
        }
    }
}
  1. In your codebase:
<script>
    export default {
        data() {
            return {
                sub: this.$route.params.sub,
                posts: [],
            }
        },
        watch: {
            '$route'(to, from) {
                this.sub = to.params.sub;
            }
        },
        methods: {
          fetchPosts: async function () {
            const url = `/reddit/'${ this.sub }/.json?limit=10`;
            try {
              const res = await (await fetch(url)).json();
              this.posts = await (res.data.children);
            } catch(err) {
              console.error(err);
            }
          }
        },
        mounted() {
          this.fetchPosts();
        },
    }
</script>

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

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

App Built with HTML and JavaScript

I am looking to create an application using HTML and JavaScript, but I could use a little guidance as I'm not yet an expert in these areas. My goal is to have the number in the middle increase by 1 every time the orange area is clicked. Can you help m ...

Executing JavaScript code following the successful loading of content through an AJAX request

I recently encountered an issue with my JavaScript code, specifically with the loadContent function not working after loading some content via AJAX in the same file. I tried using the .live() method in jQuery to solve the problem, but unfortunately, I&apo ...

Combine the arrays to utilize ng-repeat

I'm working with several arrays and I need to display them in a table using ng-repeat. Is there a way to combine arrays like name=[name1, name2] and type=[type1, type2] into a single array data=[..] so that I can use ng-repeat for data.name and data.t ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Acquire the accurate x and y coordinates upon mouse hovering

<div v-for="day in week.days" :key="day.timestamp" @mouseover="selectDate($event,day)"> </div> <div v-show="displayEvents.length!=0" ref='eventList' style= " background:red; height:mi ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

Steps to implement a body {} style on a particular vue component

To prevent interference with other components, I have been utilizing scoped styles in most of my components. However, there are certain views or components that require the use of body { overflow: hidden; }, while others do not. The issue is that I am unab ...

Gradient in Half Circle With JavaScript

How can I achieve a gradient effect within a circle using the following initial code: HTML: <div class="progresss"> <div class="barOverflow"> <div class="bar"></div> </div> <span>10</span>% </d ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

Adjusting Text Size Depending on Width

I recently used an online converter to transform a PDF into HTML. Check out the result here: http://www.example.com/pdf-to-html-converted-file The conversion did a decent job, but I'm wondering if it's feasible to have the content scale to 100% ...

Unable to update the y formatter for tooltip on Apexcharts

My current issue involves a seemingly simple task. I have created a basic formatter method to convert numbers into currency values. It appears to be functioning properly based on the y axis values being displayed with formatting like "$8,000". However, I a ...

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

What is the best way to convert this jQuery code into an AngularJS implementation?

I'm diving into the world of AngularJS and looking for a more elegant solution using AngularJS principles Controller $scope.filter = function($event, active, id) { var html = ""; if(active){ $http({method: 'GET& ...

Loading screen for specific content section

I currently have a CSS preloader implemented on my WordPress site, but I am facing an issue where the preloader hides the entire page instead of just a part of the content that I want to hide. Specifically, I would like to hide only the main content sectio ...

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

When running nodemon in an npm project without any arguments, it fails to execute the value specified in the "main" field of the package.json

My current npm project has the following folder structure: project ├── node_modules │ └── (node_modles folders) ├── server.js ├── index.js ├── index.html ├── package.json └── package-lock.json The JavaScr ...