AngularJS 2.0 http.post返回500(内部服务器错误)

时间:2016-03-30 18:15:19

标签: laravel angular

我正在尝试使用angular 2.0通过我的PHP Laravel API添加新的英雄,我总是得到500内部服务器错误响应。

我的API(laravel):创建一个新的英雄路线:

Route::group(array('prefix' => 'api/v1', 'middleware' => ['web']), function()
    {   
     //Add a new hero
    Route::post('/heroes/create', 'HeroController@store');
    });

HeroController @ store方法:(经过测试并使用Laravel表格)

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $hero = new Hero;
        $hero->name = $request->name;
        $hero->description = $request->description;
        $hero->avatar = "None";
        $hero->save();

        $heroes = Hero::paginate(5);
        return view('/heroes/index', [
        'heroes' => $heroes
    ]);
    }

Angular onSubmit()方法:(试图让它在没有表单的情况下工作..)

onSubmit(value: string): void {  
      let headers = new Headers();
    headers.append('Content-type', 'application/x-www-form-urlencoded');

    let formPayload = new URLSearchParams();
    formPayload.set('name', name.value);
    formPayload.set('description', desc.value);
    formPayload.set('_token', _token.value);

    this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create', 
                       JSON.stringify({name:'Joe',description:'wonder', _token:'knUS8vUxihTj4YJhjVkqmRBJJkVDDCABIZaRwXhN'}),
                       {headers:headers})
.map((res: Response) => res.json())
.subscribe(
        data => { this.heroes = data;
        },
        err => console.error(err),
        () => console.log('done');
      );

我得到了什么:

POST http://127.0.0.1/heroWorld/public/api/v1/heroes/create 500 (Internal Server Error)

怎么了?我试图解决它好几天,没有任何作用。

1 个答案:

答案 0 :(得分:1)

使用post类创建表单数据,但在let formPayload = new URLSearchParams(); formPayload.set('name', name.value); formPayload.set('description', desc.value); formPayload.set('_token', _token.value); this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create', formPayload.toString(), // <------ {headers:headers}) 方法中使用另一个对象。您可以尝试以下方法:

$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username'].",
'".$formValue['password']."')",
  "INSERT INTO $table_2 VALUES (NULL,
    '".$lastID."')"
  )`;

 for($i = 0; $i < count($myQueries); $i++){
     if (mysqli_query($Link, $myQueries[$i])) {
           $lastID = mysql_insert_id();
            $message = "You've sucessfully created the account!";
            echo json_encode(array('success'=>'true', 
             'action'=>'login',
              'html'=>$message, 
              'console.log'=>$Query));
    }
    else {
        $message = "Error occur in query[$i]";
        echo json_encode(array('action'=>'error',
        'html'=>$message,                   
       'console.log'=>$Query));
        exit; // stops the next query
     }
    }
 }