Reputation: 1681
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>
Upvotes: 2
Views: 819
Reputation: 316
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.
/config/index.js
file, find proxyTable
, and add this: ```
proxyTable: {
'/reddit': {
target: 'https://www.reddit.com/r',
changeOrigin: true,
pathRewrite: {
'^/reddit': ''
}
}
}
```
<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>
```
Upvotes: 1