Angular 2 http post到my laravel API
假设我有以下LaravelAngular 2 http post到my laravel API,laravel,angular,Laravel,Angular,假设我有以下Laravelstore()方法: public function store(Request $request) { $Hero = new Hero; $Hero->name = $request->name; $Hero->description = $request->description; $Hero->save(); } 它是routeroute::post('new
store()
方法:
public function store(Request $request) {
$Hero = new Hero;
$Hero->name = $request->name;
$Hero->description = $request->description;
$Hero->save();
}
它是routeroute::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发布中得到以下错误:
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))
似乎我的主体
变量有问题,但我不知道应该如何。
有什么帮助吗
我的请求:
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
您可能忘了导入标题
类。这样就不会发送内容类型
标头,并且您的服务将无法反序列化表单,因为它不知道负载实际上是一个表单
import {Http, Headers, ...} from 'angular2/http';
您可能忘了导入标题
类。这样就不会发送内容类型
标头,并且您的服务将无法反序列化表单,因为它不知道负载实际上是一个表单
import {Http, Headers, ...} from 'angular2/http';
这个错误基本上说明了一切;您的英雄对象似乎缺少名称值!你能证实你是对的吗?这是100%正确的。我使用了console.log(hero.name),它显示了我的价值。是的,但是你能记录body的价值吗?或者var_在php函数中转储name的请求值>body变量很好,只是测试了它。由于某些原因,我的angular方法将空数据发送到我的laravel或$request->name错误(?)。我无法在laravel端检查$request,无法记录或输出它,我猜这个值是多少。数据?错误本身就说明了问题;您的英雄对象似乎缺少名称值!你能证实你是对的吗?这是100%正确的。我使用了console.log(hero.name),它显示了我的价值。是的,但是你能记录body的价值吗?或者var_在php函数中转储name的请求值>body变量很好,只是测试了它。由于某些原因,我的angular方法将空数据发送到我的laravel或$request->name错误(?)。我无法在laravel端检查$request,无法记录或输出它。我猜这个值是多少。数据?是的,我没有导入头,但似乎没有解决我的问题。我的数据仍然空发送到我的laravel方法。您希望看到什么样的内容?Url编码的表单、json内容或查询参数?我也尝试了这篇文章的正文:let body={name:hero.name,description:hero.description}代码>没有成功是的,我没有导入任何标题,但似乎它没有解决我的问题。我的数据仍然空发送到我的laravel方法。您希望看到什么样的内容?Url编码的表单、json内容或查询参数?我也尝试了这篇文章的正文:let body={name:hero.name,description:hero.description}代码>没有成功