简体   繁体   中英

Why are API requests being made to the wrong URL (Vue.js 2)?

I'm fooling around trying to learn stuff (Vue.js 2 with routing) and I was wondering why whenever I was on any other routes other than the home ('/') route, said localhost url gets prepended to the appropriate url when making API calls. An example would be the following:

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

which results in something like this:

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

Below is the relevant code:

<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>

There are 2 problems in your project.
1. The request whose host is reddit can't be send within localhost.
2. if you use back quote, single quote is redundant.

IF YOU USED VUE-CLI TO INIT THE PROJECT, to solve these problem, there are 2 step you should do.

  1. in /config/index.js file, find proxyTable , and add this:

```

proxyTable: {
    '/reddit': {
        target: 'https://www.reddit.com/r',
        changeOrigin: true,
        pathRewrite: {
            '^/reddit': ''
        }
    }
}
  1. in the relevant code:

```

<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>

```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM