0

我想使用带有当前用户登录 ID 的 axios.post 发布我的表单数据。

axios.post('http://localhost:8000/api/add-property/', 
      formData, {
        headers:{
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': 'http://http://127.0.0.1:8000',
          'Access-Control-Allow-Credentials': true,
        }
      }
    ).then(function(response){ 
      console.log(response.data.message)
    }).catch(function(error){
      console.log(error)
    });

请告诉我这些事情?

  1. 用登录用户的 id 添加一些数据的 api url 应该是什么?
  2. 如何获取当前登录的用户ID?

我的后端在 laravel 中,我的商店功能控制器是这样的:-

public function AddProperty(Request $request, $id) {
    
    
        
        $validator                     =       Validator::make($request->all(),
            [
                "agency_name"                       =>  "required",
                "agency_location"                   =>  "required",
                // my rest of validations
          
            ]               
        );

        if($validator->fails()) {
            return response()->json(["status" => "failed", "validation_errors" => $validator- 
            >errors()]);
        }


        //--------------------get user id---------------------------------------------------
        $user                    =       array();

        $user = DB::table('users')->where('id', $id)->first();
        
        $user_identification     =       $user->id;

        
        //----------------------------------------------------------------------------------
        
        $agency_name                            =   $request->input('agency_name');
        $agency_location                        =   $request->input('agency_location');

        $user_id                                =   $user_identification;
        
        $propertyArray = array(
            'agency_name'                       => "$agency_name",
            'agency_location'                   => "$agency_location",

            'user_id'                           =>  $user_identification
        );
       
        $property        =       AddProperty::create($propertyArray);
        return "property added succesfully with id:".$property->id;

我添加属性的路线是:-

Route::post("add-property/{id}", "AddPropertyController@AddProperty");

当我从邮递员传递 id 时,它会将数据输入到数据库中,我对如何从反应中获取 id 并将其传递到 post api 并将数据输入到我的数据库中感到困惑。

请有人帮助我,并在此先感谢

4

2 回答 2

0

如果您使用 laravel 身份验证,您可以简单地调用

$user = Auth::user();

检索经过身份验证的用户

如果您不使用 laravel 身份验证,那么这取决于您如何实现

于 2020-08-20T15:20:45.303 回答
0

将登录的用户对象或身份验证(承载令牌)保存在浏览器的本地存储中。

然后在使用 post api 发送时,只需在 api 的标头中使用该令牌或用户 ID。

您可以像这样使用本地存储解决方案:

var userObj= JSON.parse(localStorage.getItem('userObj'));

或者您可以使用 react js props 解决方案来componentWillReceiveProps获取登录用户。

于 2021-11-11T11:54:42.573 回答