如何在Laravel中发出POST请求

如何在Laravel中发出POST请求

本文介绍了如何在Laravel中发出POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个API.获取请求作品.我尝试执行POST请求.

I created an API. Get request works. I try to perform POST request.

HomeController

<?php
class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $name = Auth::user()->name;
        $ip = Request::ip();

        $user = User::create([
            'name' => $request->input('name'),
            'ip' => $request->input('ip')
        ]);
        return $user;
    }

    public function index()
    {
        return view('home');
    }
}

我的路线

Route::get('/home', 'HomeController@index')->name('home');
Route::post('/api/person', 'HomeController@store');

我尝试通过POSTMAN发布.

I try to Post through POSTMAN.

收到消息":

错误来自哪里?

推荐答案

app/Http/Middleware/VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/api/person'
    ];
}

这是使用POSTMAN进行测试的理想选择,但是从Javascript执行API调用时,您应该发布有效的X-CSRF-TOKEN

This is ideal for testing using POSTMAN but you should post a valid X-CSRF-TOKEN when performing API calls from Javascript

在您的控制器中,您遇到了几个问题

And in your controller you have several issues

<?php

class HomeController extends Controller
{
    public function __construct()
    {
        // REMOVE THIS
        // $this->middleware('auth');
    }

    public function store(Request $request)
    {
        // UNUSED VARIABLES, REMOVE THEM
        // $name = Auth::user()->name;
        // $ip = Request::ip();

        $user = User::create([
            'name' => $request->input('name'),
            'ip' => $request->input('ip')
        ]);
        return $user;
    }

    public function index()
    {
        return view('home');
    }
}

这篇关于如何在Laravel中发出POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:45