drhzn3911 2017-07-04 09:36
浏览 81

当请求验证失败时,带有mamp 4.2.2(nginx)的Laravel 5.3提供200个HTTP状态,而不是422

I have a simple ajax request on frontend

$.ajax({
   url: '/api/marketing-research',
   dataType: 'json',
   type: 'post',
   data: this.form.data(),
   success(resp) {
       console.log(resp);
   }
});

And simple handler on backend

    public function store(MarketingResearchRequest $request)
    {
        $research = Auth::user()->addMarketingResearch($request->castAll());
        return $this->respond([
            'type' => 'store marketing research',
            'message' => 'Marketing Research successfully store.',
            'id' => $research['id'],
            'routeEdit' => route('services.marketingResearch.card', ['marketingResearch' => $research['id']]),
        ]);
    }

As you see, here is used request with validation, so if i don't pass validation, i'm expecting an error with code 422 and json response with error messages. BUT i get 200 HTTP status OK with html/text header and errors. On production server it works properly with the same code. So, where am i wrong?

MarketingResearchRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Media101\Request\Cast\Castable;

class MarketingResearchRequest extends FormRequest
{
    use Castable;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:200',
            'target' => 'max:200',
            'description' => 'string',
            'started_at' => 'required|date',
            'count_respond' => 'required|integer|min:1',
            'price' => 'required|numeric|min:10',
            'sum' => 'numeric',
            'status' => 'integer',
            'striations' => 'array',
            'striations.*.fields.',
            'striations.*.fields.volume' => 'required|numeric|min:0|max:100|nullable',
            'striations.*.fields.gender' => 'string|max:10|nullable',
            'striations.*.fields.ageFrom' => 'numeric|min:0|max:150|nullable',
            'striations.*.fields.ageOn' => 'numeric|min:0|max:150|nullable',
            'striations.*.fields.education' => 'string|max:40|nullable',
            'striations.*.fields.ideology' => 'string|max:40|nullable',
            'striations.*.fields.family_status' => 'string|max:40|nullable',
            'striations.*.fields.children' => 'boolean|nullable',
            'striations.*.fields.childrenCount' => 'numeric|max:100|nullable',
            'striations.*.fields.incomeFrom' => 'numeric|nullable',
            'striations.*.fields.incomeOn' => 'numeric|nullable',
            'striations.*.fields.politics' => 'string|max:40|nullable'
        ];
    }

    protected function casts()
    {
        return [
            'target' => 'null',
            'started_at' => 'null',
            'count_respond' => 'null',
            'price' => 'null',
            'sum' => 'null',
            'status' => 'null',
        ];
    }
}

Castable trait

<?php

namespace Media101\Request\Cast;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Allows request to be able to cast it's parameters to desired types.
 *
 * @example
 *
 * // In request model
 * public function casts()
 * {
 *     return [
 *         'birthed_at' => ['date', 'd.m.Y'],
 *         'address' => 'null'
 *     ];
 * }
 *
 * // In controller
 * $model->update($request->castAll());
 *
 * Available casts:
 * * date($format)                          - Casts to Carbon object using given format
 * * null()                                 - Casts empty string to null
 *
 * @mixin Request
 */
trait Castable
{
    /**
     * Override this method to define which attributes should this request cast
     *
     * @return array Indexed by field name, with value being array of cast name and case function arguments
     */
    abstract protected function casts();

    /**
     * Extract all parameters and cast them
     *
     * @return array
     */
    public function castAll()
    {
        return $this->castData($this->all());
    }

    /**
     * Extract only specified parameter values and cast them
     *
     * @param sting[] $fields
     * @return array
     */
    public function castOnly($fields)
    {
        return $this->castData($this->only($fields));
    }

    /**
     * Extract all the parameters except specified and cast them
     *
     * @param string[] $fields
     * @return array
     */
    public function castExcept($fields)
    {
        return $this->castData($this->except($fields));
    }

    /**
     * Extract subarray from field and casts all the values there
     *
     * @param string $field
     * @return array
     */
    public function castNested($field)
    {
        return $this->castData($this->input($field, []));
    }

    /**
     * Extract input value and casts it
     *
     * @param string $field
     * @return mixed
     */
    public function castInput($field, $default = null)
    {
        $casts = $this->casts();
        return isset($casts[$field]) && $this->exists($field)
            ? $this->castValue($this->input($field, $default), $casts[$field])
            : $this->input($field, $default);
    }

    /**
     * @param array $data
     * @return array
     */
    protected function castData($data)
    {
        foreach ($this->casts() as $attribute => $cast) {
            if (isset($data[$attribute]) || array_key_exists($attribute, $data)) {
                $data[$attribute] = $this->castValue(@$data[$attribute], $cast);
            }
        }
        return $data;
    }

    /**
     * @param mixed $value
     * @param array|string|callback $cast
     * @return mixed
     */
    protected function castValue($value, $cast)
    {
        if (!is_string($cast) && is_callable($cast)) {
            return $cast($value);
        } else {
            $args = (array) $cast;
            $method = array_shift($args);
            array_unshift($args, $value);
            return call_user_func_array([$this, 'castTo' . Str::camel($method)], $args);
        }
    }

    // The cast methods

    /**
     * @param $input
     * @param string $format
     * @return Carbon|null
     */
    protected function castToDate($input, $format)
    {
        return !isset($input) || $input === '' ? null : Carbon::createFromFormat($format, $input);
    }

    /**
     * @param string $input
     * @return string|null
     */
    protected function castToNull($input)
    {
        return $input === '' ? null : $input;
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)