Angular 2 http发布到我的laravel API

时间:2016-04-10 17:14:36

标签: laravel angular

假设我有以下Laravel store()方法:

public function store(Request $request) {
        $Hero = new Hero;
        $Hero->name = $request->name;
        $Hero->description = $request->description;
        $Hero->save();
    }

这是路线Route::post('newhero', 'HeroController@store');

当用户点击按钮时,我想使用Angular 2将数据发布到上述方法。我的数据不是来自表格。

我的角度方法:

addHero(hero) {
    let body = "name=" + hero.name + "&description=" + hero.description;
    let headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.http
    .post('http://localhost/heroland/public/api/v1/newhero', 
      body, {
        headers: headers
      })
    .map(response => response.json())
    .subscribe(
      response => this.data;
    );
    }

Angular发布数据,我在laravel POST中收到以下错误:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into `heroes` (`name`, description`,`updated_at`, `created_at`) values (, , , 2016-04-10 17:10:09, 2016-04-10 17:10:09))

我的body变量似乎有问题,但我不知道它应该如何。 有什么帮助吗?

我的要求:

POST /myURL/ HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate
Accept-Language: he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4
Connection:      keep-alive
Content-Length:  38
Content-Type:    text/plain;charset=UTF-8
Cookie:          XSRF-TOKEN=myToken
Host:            localhost
Origin:          http://localhost:3000
Referer:         http://localhost:3000/
User-Agent:      Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36

name=1&description=100

1 个答案:

答案 0 :(得分:0)

您可能忘记导入Headers课程。这样就不会发送Content-Type标头,并且您的服务无法反序列化表单,因为它不知道有效负载实际上是一个表单。

import {Http, Headers, ...} from 'angular2/http';