Laravel + Vue + Axios POST方法问题

6

我正在开发一个 Laravel 5.6 项目,它存储在 VPS 上(我们称其为“生产环境”,尽管没有创建此类环境)。

我们还将 Plesk 和 Github 结合使用,手动从本地环境部署 Web 应用程序到服务器上。

问题是当我从 API 中加载一些数据时,它们返回错误 405 方法不允许 (GET)... 但实际上它们在 app.jsroutes/api.php 中注册为 POST

最好的事情是,在我的本地环境中,它们工作得非常完美。

以下是一些信息:

服务器:

  • Ubuntu Server 14.04
  • Apache / MySQL
  • PHP 7.2.5

我的电脑:

  • Windows 10 with XAMPP
  • Apache / MySQL
  • PHP 7.2.2

每个浏览器中的开发者工具:

请求方法:GET
状态码: 405 方法不允许

这是在 app.js 中的代码:

loadCountries: function loadCountries(total) {
    axios.post('/api/properties/countries/').then(function (response) {
        app.countries = response.data;
    });

    total = total <= this.countries.length ? total : this.countries.length;

    if (total) {
        var newArr = [];
        for (i = 0; i < total; i++) {
            newArr.push(this.countries[i]);
        }
        this.countries = newArr;
    }
},

注意:如果我在开发者工具中编辑同一个请求,然后将其作为POST请求发送,它会返回一切正常,因此API在POST请求上似乎正常工作。

这个回答可能与您的问题相关 https://dev59.com/M1YN5IYBdhLWcg3w9Mbr - Ryan Kozak
我找不到那个答案...它解决了我的问题。请回答。谢谢。 - Maramal
@Maramal:如果在Postman中可以工作,那么尝试从请求中删除“/”。像这样尝试:'/api/properties/countries',因为我认为它试图查找'/api/properties/countries/',而且在你的路由中没有定义! - Hiren Gohel
@kozak 请以答案的形式发布。 - Maramal
@Maramal,NP,很高兴它起作用了。 - Ryan Kozak
2个回答

4

尝试从您的url中删除尾部斜杠。

例如:

/api/properties/countries

替换你原来的app.js文件中的那一行代码,将得到如下结果:
loadCountries: function loadCountries(total) {
axios.post('/api/properties/countries').then(function (response) {
    app.countries = response.data;
});

total = total <= this.countries.length ? total : this.countries.length;

if (total) {
    var newArr = [];
    for (i = 0; i < total; i++) {
        newArr.push(this.countries[i]);
    }
    this.countries = newArr;
}

},


0

我曾经遇到过这个问题,解决方法是创建一个计算属性,包含完整的URL,像这样:

computed: {
    sendAnswersUrl: function () {
        return window.location.protocol + "//" + window.location.hostname, +  "/api/properties/countries";
     }
  }

然后使用axios进行发布

axios.post(this.sendAnswersUrl, {
          group: this.id,
        })
        .then(data => {})
        .catch(() => {});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接