Javascript 为什么向错误的URL(Vue.js 2)发出API请求?
我在尝试学习一些东西(Vue.js 2和路由),我想知道为什么每当我在主('/')路由之外的任何其他路由上时,localhost url都会在进行API调用时预先添加到相应的url。例如:Javascript 为什么向错误的URL(Vue.js 2)发出API请求?,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我在尝试学习一些东西(Vue.js 2和路由),我想知道为什么每当我在主('/')路由之外的任何其他路由上时,localhost url都会在进行API调用时预先添加到相应的url。例如: const url = `'https://www.reddit.com/r/'${ this.sub }/.json?limit=10'`; // this.sub being the corresponding subreddit string 其结果如下: '' 以下是相关代码: <script
const url = `'https://www.reddit.com/r/'${ this.sub }/.json?limit=10'`; // this.sub being the corresponding subreddit string
其结果如下:
''
以下是相关代码:
<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>
导出默认值{
数据(){
返回{
sub:this.$route.params.sub,
员额:[],
}
},
观察:{
“$route”(到,从){
this.sub=to.params.sub;
}
},
方法:{
fetchPosts:async函数(){
常量url=`'https://www.reddit.com/r/'${this.sub}/.json?limit=10'`;
试一试{
const res=await(await fetch(url)).json();
this.posts=wait(res.data.children);
}捕捉(错误){
控制台错误(err);
}
}
},
安装的(){
this.fetchPosts();
},
}
您的项目中有两个问题。1.主机为reddit的请求无法在localhost内发送。
2.如果使用反向报价,则单个报价是多余的 如果使用VUE-CLI初始化项目,要解决这些问题,应执行两个步骤
/config/index.js
文件中,找到proxyTable
,并添加以下内容:
导出默认值{
数据(){
返回{
sub:this.$route.params.sub,
员额:[],
}
},
观察:{
“$route”(到,从){
this.sub=to.params.sub;
}
},
方法:{
fetchPosts:async函数(){
常量url=`/reddit/'${this.sub}/.json?limit=10`;
试一试{
const res=await(await fetch(url)).json();
this.posts=wait(res.data.children);
}捕捉(错误){
控制台错误(err);
}
}
},
安装的(){
this.fetchPosts();
},
}
```谢谢!实际上,正如您所指出的,我忘记了去掉URL模板文本中的(单)引号。这样做就成功了。
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>