Home > Mobile >  Fetching data via react from laravel route
Fetching data via react from laravel route

Time:06-13

I have implemented the following function in my laravel app that used Laravel Framework 8.83.16:

    public function checkIdentifier($physicalItem_identifier)
    {
        try {
            $con = "mysql";

            $res = DB::connection($con)->table('identifiers')
                ->select('*')
            ->where('physicalItem_identifier', '=', $physicalItem_identifier)
            ->where('available', '=', TRUE)
            ->get();

            if ($res->count()) {
                return response()->json(['exists' => true],200);
            } else {
                return response()->json(['exists' => false], 200);
            }
        } catch (\Exception $e) {
            Log::error($e);
            return response()->json(['exists' => 'error'],200);
        }
    }

My route looks like the following:

Route::get('v1/checkIdentifier/{physicalItem_identifier}', [ItemController::class,'checkIdentifier']);

The following url works for my laravel application:

http://localhost/project/public/v1/checkIdentifier/testIdentifier

For my react-app I am using:

{
  "name": "react-app",
  "version": "1.0",
  "private": true,
  "dependencies": {
    "babel-eslint": "10.0.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^6.3.0",
    "react-scripts": "3.2.0",
    "redux": "^4.1.1",
    "redux-thunk": "^2.3.0",
    "web-vitals": "^1.0.1",
    "web3": "^1.6.1",
    "web3-eth-contract": "^1.5.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "autoprefixer": "^10.4.7",
    "postcss": "^8.4.14",
    "tailwindcss": "^3.0.24"
  }
}

I have created the following function to check if the identifier exists:

import { Routes, Route, useParams } from "react-router-dom";

function MintComponent() {

  const { identifierUrl } = useParams();

  const getData = async () => {
      let url = "http://localhost/project/public/v1/checkIdentifier/"   identifierUrl;

    try {
      const response = await fetch(url);
      const data = await response.json();
      // enter you logic when the fetch is successful
      console.log(data);
    } catch (error) {
      // enter your logic for when there is an error (ex. error toast)
      console.log(error);
    }
    
    ...
  };

When the above function runs in my react app I get:

'TypeError: Failed to fetch\n    at getData (http://localhost:3000/static/js/main.chunk.js:210:32)\n    at onClick (http://localhost:3000/static/js/main.chunk.js:295:7)\n    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/1.chunk.js:77068:18)\n    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/1.chunk.js:77117:20)\n    at invokeGuardedCallback (http://localhost:3000/static/js/1.chunk.js:77177:35)\n    at invokeGuardedCallbackAndCatchFirstError (http://localhost…1.chunk.js:79176:7)\n    at dispatchEvent (http://localhost:3000/static/js/1.chunk.js:79094:23)\n    at unstable_runWithPriority (http://localhost:3000/static/js/1.chunk.js:116209:16)\n    at runWithPriority$1 (http://localhost:3000/static/js/1.chunk.js:84474:14)\n    at discreteUpdates$1 (http://localhost:3000/static/js/1.chunk.js:95396:18)\n    at discreteUpdates (http://localhost:3000/static/js/1.chunk.js:76878:16)\n    at dispatchDiscreteEvent (http://localhost:3000/static/js/1.chunk.js:79060:7)'

I also checked the network tab and it seems to be a CORS error:

enter image description here

Any suggestions why the fetch does not work for my react-app on my local machine?

I appreciate your replies!

CodePudding user response:

As a quick fix for the CORS error, you can attach the Access-Control-Allow-Origin header whenever you return a response:

return response()->json(['exists' => true],200)->header('Access-Control-Allow-Origin', 'http://localhost:3000');

A more thorough solution would be to use a CORS middleware, such as in this post (just don't set the value to *).

  • Related