首页 > 解决方案 > Axios 发布到错误的 URL

问题描述

这是我在 CreatePage.vue 页面上使用的方法

  methods: {
async createPost() {
  try {
    await PostService.createPost(this.form);
  } catch (err) {
    console.log(err);
  }
}
  }
};

这是 PostService 类

   const axios = require('axios')
   const url = 'api/post/'

class PostService {
static async createPost(post) {
    return axios.post(url + 'create', post)
}

}

这是代理的 vue.config

const path = require('path')

module.exports = {
outputDir: path.resolve(__dirname, '../server/public'),
devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:3000/',
        }
    }
},
}

当我发出一个应该转到 http://localhost:3000/api/post/create的发布请求时

问题在于它将当前页面地址附加到请求的开头,例如
http://localhost:3000/posts/api/post/create (帖子页面,如果在仪表板页面上,将附加仪表板)

标签: javascriptnode.jsvue.jsaxios

解决方案


问题出在您的 PostService 类中,因为您没有在 URL 中包含“/”,请将其更改为

const axios = require('axios')
const url = '/api/post/'

class PostService {
  static async createPost(post) {
    return axios.post(url + 'create', post)
  }
}
``

推荐阅读