Reputation: 24472
I'm trying to use angular 2.0 to add a new hero via my PHP Laravel API and I always get 500 Internal server error response.
My API (laravel): Create a new hero route:
Route::group(array('prefix' => 'api/v1', 'middleware' => ['web']), function()
{
//Add a new hero
Route::post('/heroes/create', 'HeroController@store');
});
HeroController@store method: (Tested and works with a Laravel form)
/**
* 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() Method: (trying to make it work without a form..)
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');
);
What I get:
POST http://127.0.0.1/heroWorld/public/api/v1/heroes/create 500 (Internal Server Error)
What's wrong? I'm trying to fix it for several days, nothing works.
Upvotes: 1
Views: 3664
Reputation: 202206
You create a form data using the URLSearchParams
class but you use another object in the post
method. You could try the following instead:
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})
Upvotes: 1