Angular 2+和Laravel - 内部服务器错误

时间:2017-06-12 10:44:17

标签: laravel angular

对于从Angular到Laravel的发布请求,我收到错误(内部服务器错误)。但它在Postman中成功运作。

api.php

    <?php
    use Illuminate\Http\Request;

    Route::post('/addHouse', [
        'uses' => 'HouseController@postHouse'
    ]);

HouseController.php

    public function postHouse(Request $request)
{
    $house=new House();
    $house->houseName=$request->input('houseName');
    $house->type=$request->input('type');
    $house->for=$request->input('for');
    $house->address=$request->input('address');
    $house->price=$request->input('price');
    $house->description=$request->input('description');
    $house->bedrooms=$request->input('bedrooms');
    $house->bathrooms=$request->input('bathrooms');
    $house->area=$request->input('area');
    $house->save();
    return response()->json([
        'house'=>$house
    ],201);
}

Cors.php(中间件)

     public function handle($request, Closure $next)
     {
         return $next($request)
           ->header('Access-Control-Allow-Origin','*')
           ->header('Access-Control-Allow-Methods','Get, POST, PUT, PATCH, DELETE, OPTIONS')
           ->header('Access-Control-Allow-Headers', 'Content-type, Authorization');
     }

在Angular house.service.ts

    addHouse(content)  {
        console.log(content);
        const body = JSON.stringify({
        content: content
    });
    const headers = new Headers({
       'Content-Type':'application/json'
    });
   return this._http.post('http://localhost:8000/api/addHouse', body, {
       headers: headers
   });
  }

我的错误 - &gt; POST http://localhost:8000/api/addHouse 500(内部服务器错误)

1 个答案:

答案 0 :(得分:0)

我通过更改addHouse函数解决了这个问题。谢谢大家..

    addHouse(data) {
        var headers = new Headers();
        headers.append (
           'Content-type','application/json'
        );
    return this._http.post('http://localhost:8000/api/addHouse', JSON.stringify(data), {
                   headers:headers
                  }).map(res => res.json());
    }