无法使用laravel控制器保存反应本地stringfy数据

时间:2018-07-07 16:14:50

标签: reactjs react-native laravel-5 laravel-5.2

这是React本机代码

    fetch('https://sssdff.000webhostapp.com/save/', {
        method: 'post',
        header:{
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body:JSON.stringify({
            name: "john",
            price: 145,

        })

    })
    .then((response) => response.json())
        .then((response) =>{
            alert("sucess");
        })
        .catch((error)=>{
            alert("error"+error);
            console.error(error);
        });

这是Laravel代码

  public function save(Request $request)
{

    $data = $request->name;

    $coin = new Coin();
    $coin->name=$data;
    $coin->price= 125;
    $coin->save();


 return response()->json([ 'state' => 'success' ]);

}

当我传递一个字符串值时,例如$ coin-> name =“ jack”;成功,并将数据保存到数据库。但是当我尝试传递参数值时出现错误。

1 个答案:

答案 0 :(得分:0)

Try directly it will work, do not stringify.
`
body:{
name: "john",
price: 145,
}
`
inside laravel:

`$data = request()->all();
$coin = new Coin();
$coin->name=$data['name'];
$coin->price= $data['price'];
$coin->save();
`