【问题标题】:Use axios with Vue and Laravel for post request使用 axios 和 Vue 和 Laravel 进行发布请求
【发布时间】:2021-04-28 14:39:58
【问题描述】:

我正在尝试查看 Laravel + Vue,但我在 vista 方面遇到了问题。 如何通过 axios 正确发送数据? 看看我是怎么做到的。

 <button onClick="addVote(question.id)">Vote</button>
data() {
            return {
              questions:[],
              percentages:[],
              vote:''
            }
        },
        methods: {
            getQuestions(){
                axios.get('/questionlist')
                    .then((response)=>{
                       this.questions = response.data.question
                    })
            },
            getPercentages(){
                axios.get('/getpercentage')
                    .then((response)=>{
                       this.percentages = response.data.percentage
                    })
            },
            addVote(id) {
                axios.post(`/vote/${id}`, data);
            }
        },
        created() {
            this.getQuestions(),
            this.getPercentages(),
            this.addVote()
        }

这些是视图中接收数据和发送数据的方法。 最后一个是我想向服务器发送请求并能够为每个投票添加一个 + 的投票方法。

这也是控制器

 public function vote($id) {
        $question = Question::find($id);
        if(Auth::user()->votes == 0) {
            $question->increment('votes', 1);
            $question->increment('totalvotes', 1);
            Auth::user()->update([
                'votes' => '1'
            ]);
            Alert::success("Success", 'Your vote has been added');
        }
        return response()->json($question);
    }
Route::POST('/vote/{id}',          'QuestionController@vote');

我的问题是,在这些情况下我做错了什么?

【问题讨论】:

标签: php laravel vue.js


【解决方案1】:

由于是 POST 请求,因此无需在 URL 中添加参数。你应该在 Laravel 中使用 API 路由(api.php)并且可以像这样构造它

Route::POST('/vote', 'QuestionController@vote');

由于您将其作为 API 路由放置在 api.php 中,因此它会以 /api 为前缀。 所以你的 axios 调用应该是这样的:

addVote(id) {
            axios.post(`/api/vote`, {id: id});
}

现在在 QuestionController 的投票方法中将如下所示:

public function vote(Request $request)
{
    dd($request);
}

您将看到请求数据的转储并决定如何处理它。

【讨论】:

  • 我会得到 addVote() undefined
猜你喜欢
  • 2017-10-02
  • 2018-06-27
  • 2020-06-06
  • 2019-02-20
  • 2021-12-25
  • 2018-02-15
  • 2020-02-14
  • 2017-06-05
  • 2020-06-13
相关资源
最近更新 更多