首页 > 解决方案 > 如何使分支 API 从 React(前端)和 Lumen Laravel(后端)工作?

问题描述

我想开发一个使用 ReactJS 作为前端的网站,两个 API 项目都在 Lumen Laravel 作为后端开发。我想将图像从前端发布到 API A,API A 将再次将图像发布到 API B,API B 将使用 Matlab 处理图像。在我的情况下,当我将图像发布到 API A 时,图像不会再次将图像发布到 API B。但是当我更改代码时,将图像发布到 API B,由 API B 处理的图像。我不'不知道为什么 API A 不能再次将图像从前端发布到 API B。

这是我的代码。

PostImage.js

postImage(data, token) {
        const path = `image`;

        const formData = new FormData();

         formData.append("file", data.file);
         formData.append("matrix", data.matrix);
         formData.append("color", data.color);
        
         return axios.post(`${API_A}/${path}`, formData, {        
            headers: {
              'Content-Type': 'multipart/form-data',
              token: token,
            },
            params: {
                token: token,
            },
        })
        .catch((error) => {
            if (error.response) {
                return Promise.reject({
                    message: error.response.data.error,
                    code: error.response.status
                });
            } else if (error.request) {
              console.log(error.request);
              throw error;
            } else {
              console.log('Error', error.message);
              throw error;
            }
        });
    }

和 API A

 public function postImage(Request $request)
    {
        $all_ext = implode(',', $this->image_ext);

        $this->validate($request, [
            'matrix' => 'integer',
            'color' => 'integer',
            'file' => 'required|file|mimes:' . $all_ext . '|max:' . $this->max_size,
        ]);

        $model = new UserImage();

        $file = $request->file('file');

        $store = Storage::put('public/upload', $file);
        dd($store);
        
        try {
            $response = $this->client->request('POST', 'http://apiB/imageProcess', [
                'multipart' => [
                    [
                        'name'     => 'matrix',
                        'contents' => (int) $request->get('matrix', 2),
                        'headers'  => [ 'Content-Type' => 'multipart/form-data']
                    ],
                    [
                        'name'     => 'color',
                        'contents' => (int) $request->get('color', 1),
                        'headers'  => [ 'Content-Type' => 'multipart/form-data']
                    ],
                    [
                        'name'     => 'img_file',
                        'contents' => fopen(storage_path('app/' . $store), 'r'),
                        'filename' => $file->getClientOriginalName(),
                        'headers'  => [ 'Content-Type' => 'multipart/form-data']
                    ],
                ]
            ]);

            $image = $response->getBody()->getContents();

            $filePath = '/public/' . $this->getUserDir();
            $fileName = time().'.jpeg';

            if ($result = Storage::put($filePath . '/' . $fileName, $image)) {
                $generated =  $model::create([
                    'name' => $fileName,
                    'file_path' => $filePath,
                    'type' => 'motif',
                    'customer_id' => Auth::id()
                ]);

                return response()->json($generated);
            }
            
        } catch (RequestException $e) {
            echo $e->getRequest() . "\n";
            if ($e->hasResponse()) {
                echo $e->getResponse() . "\n";
            }

            return response($e->getResponse());
        }

        return response()->json(false);
   }

API B

 public function processImage(Request $request){
    $msg = $this->validateParam($request);
    if($msg != ''){
      return response()->json(array(
        'message'=>$msg.' is not valid'
      ), 200);
    }
    ini_set('max_execution_time', 1500);

    $sourceFolderPath = 'public/img_src/param_temp/before/';
    $resultFolderPath = base_path('public\img_src\param_temp\after');

    $matrix = $request->input('matrix');
    $color = $request->input('color');
    $image = $request->file('img_file');
    $extension = image_type_to_extension(getimagesize($image)[2]);
    $nama_file_save = $sourceFileName.$extension;
    $destinationPath = base_path('public\img_src\param_temp\before'); // upload path
    $image->move($destinationPath, $nama_file_save);

    $sourceFile = $destinationPath .'\\' . $nama_file_save;
    $resultFile = $resultFolderPath .'\\'. $resultFileName.'.jpg';

    $command = "matlab command";

    exec($command, $execResult, $retval);
    if($retval == 0){
    
      $destinationPath = base_path('public\img_src\param_temp\after');
      $sourceFile = $destinationPath .'\\' . $resultFileName.'.jpg';
      $imagedata = file_get_contents($sourceFile);
      
    if(!$imagedata) return $this->errorReturn();
      $base64 = base64_encode($imagedata);
      $data = base64_decode($base64);

      return response($data)->header('Content-Type','image/jpg');
    }
    return $this->errorReturn();
  }

保存在 API A 中但未处理到 API B 的图像

我不知道我的代码哪里出了问题,但是如果您有任何建议,这对我很有帮助

标签: phpreactjslaravellumen

解决方案


推荐阅读